Spiral Matrix IV (LeetCode 2326): Solution and Explanation

Medium
Array
Linked List
Matrix
Simulation

Given the size m x n of a matrix and the head of a linked list, write the list values into the matrix in clockwise spiral order from the top-left corner and fill any cells left over with -1.

Intuition

The spiral is just a walk that goes straight until it hits something and then turns right. The things it can hit are the edge of the matrix and cells it already wrote.

If the matrix starts full of -1, a cell that is not -1 has been written. Node values are between 0 and 1000, so -1 can never be confused with real data.

The same pre-fill also answers the second half of the problem for free: when the list ends early, the cells the walk never reached already hold -1.

Directions cycle right, down, left, up. Storing them as (dr, dc) pairs in that order means a clockwise turn is just d = (d + 1) % 4.

Approach: Simulate the spiral with a direction vector

  1. Create an m x n matrix filled with -1. Set r = c = 0 and d = 0 (heading right).
  2. While the current node exists, write node.val at (r, c).
  3. Compute the next cell (r + dr, c + dc). If it is outside the matrix or not -1, set d = (d + 1) % 4 and recompute it.
  4. Move to the next cell and to node.next.
  5. Return the matrix once the list is used up.

Step-by-step example

m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
  1. Write 3, 0, 2, 6, 8 across row 0. After 8 at (0, 4), the peek to (0, 5) is off the grid, so turn down.
  2. Write 1 at (1, 4) and 7 at (2, 4). The peek to (3, 4) is off the grid, so turn left.
  3. Write 9, 4, 2, 5 at (2, 3) through (2, 0). The peek to (2, -1) is off the grid, so turn up.
  4. Write 5 at (1, 0). The peek to (0, 0) finds 3 already there, so turn right.
  5. Write 0 at (1, 1). The list ends, so (1, 2) and (1, 3) keep -1. Result: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]].

Code: Python, Java, C++

1class Solution:
2    def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
3        grid = [[-1] * n for _ in range(m)]
4        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
5        r = c = d = 0
6        node = head
7        while node:
8            grid[r][c] = node.val
9            nr, nc = r + dirs[d][0], c + dirs[d][1]
10            if not (0 <= nr < m and 0 <= nc < n) or grid[nr][nc] != -1:
11                d = (d + 1) % 4
12                nr, nc = r + dirs[d][0], c + dirs[d][1]
13            r, c = nr, nc
14            node = node.next
15        return grid
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Building the -1 matrix touches every cell once, and the walk does constant work per node, with at most m * n nodes.

Space

O(1)

Besides the m x n output matrix, only the position, direction and node pointer are stored.

Other approaches

Shrinking boundaries (time O(m * n), space O(1))

Keep top, bottom, left and right bounds and fill one side of the current ring at a time, shrinking the bound after each side. Stop as soon as the list runs out. Same cost, but more index bookkeeping and more places to make an off-by-one error.

Copy to an array first (time O(m * n), space O(L))

Read the list into an array, then reuse a Spiral Matrix II style fill. It works, but it spends O(L) extra memory for no gain.

Common mistakes

  • Using 0 as the empty marker. Node values can be 0, so a cell holding a real 0 would look empty and the walk would write over it.
  • Turning only at the matrix edge. Inner rings need a turn when the next cell is already filled.
  • Peeking out of bounds before checking the bounds. Test 0 <= nr < m and 0 <= nc < n first, then read grid[nr][nc].
  • Forgetting the leftover cells. If the matrix was created with 0, cells the list never reaches must still be set to -1.

Frequently asked questions

Can the walk ever need two turns in a row?

No. After a turn the next cell is always free while nodes remain, because the list has at most m * n nodes and the spiral visits cells in a fixed order that never boxes itself in before the grid is full.

What if the list has exactly m * n nodes?

Every cell gets a value and no -1 remains. The last turn check may peek at a filled cell, but the loop ends right after because node.next is null.

How is this different from Spiral Matrix II?

Spiral Matrix II writes 1 to n squared into a square matrix. Here the values come from a linked list of any length up to m * n, the matrix can be rectangular, and unused cells must be -1.