Skip to main content
LeetCode 2326, Medium. Topics: Array, Linked List, Matrix, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 21 parametrized pytest cases, and a playground notebook:

Problem

You are given two integers <code>m</code> and <code>n</code>, which represent the dimensions of a matrix. You are also given the <code>head</code> of a linked list of integers. Generate an <code>m x n</code> matrix that contains the integers in the linked list presented in <strong>spiral</strong> order <strong>(clockwise)</strong>, starting from the <strong>top-left</strong> of the matrix. If there are remaining empty spaces, fill them with <code>-1</code>. Return <em>the generated matrix</em>.

Examples

Example 1
Example 2

Constraints

  • 1 <= m, n <= 10^5
  • 1 <= m * n <= 10^5
  • The number of nodes in the list is in the range [1, m * n].
  • 0 <= Node.val <= 1000

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026