Spiral Matrix II (LeetCode 59): Solution and Explanation

Medium
Array
Matrix
Simulation

Given a positive integer n, build an n × n matrix containing the numbers 1 through n², placed in clockwise spiral order starting from the top-left corner and moving inward.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

One way to think about the spiral is as a walker who moves in a direction until hitting a wall or an already-filled cell, then turns right. You can code exactly that with a direction array and a check on each step. It works, but every step needs a bounds check and a visited check, and the turning logic is easy to get subtly wrong.

A cleaner view is to see the spiral as a series of rings, like layers of an onion. Each ring is four straight runs: across the top row from left to right, down the right column, back along the bottom row from right to left, and up the left column. After you finish a run, that row or column is complete and will never be touched again, so you can shrink the boundary on that side by one.

That suggests keeping four variables, top, bottom, left and right, which describe the rectangle still to be filled. Each run walks along one edge of that rectangle and then pulls that edge inward. Because the matrix is square, the rectangle stays square as it shrinks, and when n is odd the final ring is a single cell that the top-row run fills. After that, the remaining runs have empty ranges, so they do nothing, and the outer loop ends once num passes n².

Approach: Layer-by-layer simulation with four boundaries

  1. Create an n × n matrix of zeros and set top = 0, bottom = n - 1, left = 0, right = n - 1, and num = 1.
  2. While num <= n * n, fill the top row from left to right, then increment top.
  3. Fill the right column from top down to bottom, then decrement right.
  4. Fill the bottom row from right back to left, then decrement bottom.
  5. Fill the left column from bottom up to top, then increment left.
  6. Each placement writes num and increments it; when the loop exits, return the matrix.

Step-by-step example

n = 3
  1. Top row: write 1, 2, 3 into row 0, columns 0 to 2. Now top = 1.
  2. Right column: write 4 at (1, 2) and 5 at (2, 2). Now right = 1.
  3. Bottom row, right to left: write 6 at (2, 1) and 7 at (2, 0). Now bottom = 1.
  4. Left column, bottom to top: write 8 at (1, 0). Now left = 1.
  5. num is 9, still at most 9, so the loop runs again. The top-row run covers only column 1, writing 9 at (1, 1). The other three runs have empty ranges, and num becomes 10, ending the loop.
  6. The result is [[1, 2, 3], [8, 9, 4], [7, 6, 5]].

Code: Python, Java, C++

1class Solution:
2    def generateMatrix(self, n: int) -> List[List[int]]:
3        matrix = [[0] * n for _ in range(n)]
4        top, bottom, left, right = 0, n - 1, 0, n - 1
5        num = 1
6        while num <= n * n:
7            for i in range(left, right + 1):
8                matrix[top][i] = num
9                num += 1
10            top += 1
11            for i in range(top, bottom + 1):
12                matrix[i][right] = num
13                num += 1
14            right -= 1
15            for i in range(right, left - 1, -1):
16                matrix[bottom][i] = num
17                num += 1
18            bottom -= 1
19            for i in range(bottom, top - 1, -1):
20                matrix[i][left] = num
21                num += 1
22            left += 1
23        return matrix

Time and space complexity

Time

O(n²)

Every one of the n² cells is written exactly once, and each write is constant work. The empty runs at the end add only a constant amount.

Space

O(n²)

The output matrix itself holds n² integers. Apart from the output, only a handful of integer variables are used, so the auxiliary space is O(1).

Other approaches

Direction vector simulation (time O(n²), space O(n²) for the output, O(1) extra)

Keep a position and a direction from the list right, down, left, up. Move forward while the next cell is inside the grid and still zero; otherwise turn clockwise. It reuses the matrix itself as the visited marker and generalizes easily to other walking patterns.

Common mistakes

  • Updating a boundary before finishing the run on that edge, or forgetting to update it at all, which causes corners to be written twice.
  • Using the wrong range end in Python. The bottom row run is range(right, left - 1, -1), and dropping the - 1 skips the leftmost cell.
  • Reusing this exact loop for the rectangular Spiral Matrix problem. With unequal dimensions, the later runs in a pass can overwrite cells unless you recheck top <= bottom and left <= right between runs.
  • Mixing up rows and columns in the vertical runs. The right column run writes matrix[i][right], not matrix[right][i].

Frequently asked questions

Why is Spiral Matrix II O(n²)?

The matrix has n² cells and each one is filled exactly once. You cannot do better because the output alone has n² entries.

What happens to the center cell when n is odd?

On the last pass the boundaries collapse to a single cell, and the top-row run writes the final number there. The remaining runs have empty ranges, so nothing else is overwritten.

How is this different from Spiral Matrix?

Spiral Matrix reads an existing matrix in spiral order, while this version writes numbers in that order. The boundary technique is identical, but reading a non-square matrix needs extra checks between runs.