Spiral Matrix II (LeetCode 59): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create an
n × nmatrix of zeros and settop = 0,bottom = n - 1,left = 0,right = n - 1, andnum = 1. - While
num <= n * n, fill the top row fromlefttoright, then incrementtop. - Fill the right column from
topdown tobottom, then decrementright. - Fill the bottom row from
rightback toleft, then decrementbottom. - Fill the left column from
bottomup totop, then incrementleft. - Each placement writes
numand increments it; when the loop exits, return the matrix.
Step-by-step example
n = 3
- Top row: write 1, 2, 3 into row 0, columns 0 to 2. Now
top = 1. - Right column: write 4 at (1, 2) and 5 at (2, 2). Now
right = 1. - Bottom row, right to left: write 6 at (2, 1) and 7 at (2, 0). Now
bottom = 1. - Left column, bottom to top: write 8 at (1, 0). Now
left = 1. numis 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, andnumbecomes 10, ending the loop.- 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 matrix1class Solution {
2 public int[][] generateMatrix(int n) {
3 int[][] matrix = new int[n][n];
4 int top = 0, bottom = n - 1, left = 0, right = n - 1;
5 int num = 1;
6 while (num <= n * n) {
7 for (int i = left; i <= right; i++) matrix[top][i] = num++;
8 top++;
9 for (int i = top; i <= bottom; i++) matrix[i][right] = num++;
10 right--;
11 for (int i = right; i >= left; i--) matrix[bottom][i] = num++;
12 bottom--;
13 for (int i = bottom; i >= top; i--) matrix[i][left] = num++;
14 left++;
15 }
16 return matrix;
17 }
18}1class Solution {
2public:
3 vector<vector<int>> generateMatrix(int n) {
4 vector<vector<int>> matrix(n, vector<int>(n));
5 int top = 0, bottom = n - 1, left = 0, right = n - 1;
6 int num = 1;
7 while (num <= n * n) {
8 for (int i = left; i <= right; i++) matrix[top][i] = num++;
9 top++;
10 for (int i = top; i <= bottom; i++) matrix[i][right] = num++;
11 right--;
12 for (int i = right; i >= left; i--) matrix[bottom][i] = num++;
13 bottom--;
14 for (int i = bottom; i >= top; i--) matrix[i][left] = num++;
15 left++;
16 }
17 return matrix;
18 }
19};Time and space complexity
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.
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- 1skips 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 <= bottomandleft <= rightbetween runs. - Mixing up rows and columns in the vertical runs. The right column run writes
matrix[i][right], notmatrix[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.