LeetCode #59 Medium

Spiral Matrix II

Spiral Matrix II is LeetCode 59 (Medium). Given a positive integer n, build an n × n grid that holds the numbers 1 to n², placed in clockwise spiral order starting from the top-left corner.

With n at most 20 the grid has at most 400 cells, so writing each cell directly is all the work there is.

Constraints
  • 1 <= n <= 20
arraymatrixsimulation
Open on LeetCode ↗
02

Intuition

Fill the grid the way you would paint a square frame, from the outside in. Four walls, top, bottom, left and right, mark the square still blank. One lap paints its top row, right column, bottom row and left column, and each wall steps inward after its side is done. A single counter hands out 1, 2, 3 and so on, so the only real job is to visit every cell exactly once, in spiral order.

Because the grid is square, the walls close in evenly from all four sides. The loop is never left with a long thin strip, which is what forces extra checks in the reading version of this walk.

How to spot this pattern

"Write numbers into a grid along a path" is the reading walk of Spiral Matrix run in reverse: the same four walls, with each visit storing a value instead of collecting one.

03

Approach

Try it first

Before reading on, fill a 4 × 4 grid by hand with four walls and write down the wall values at the start of the second lap. Then check what each of the four loops does on that 2 × 2 lap, and whether any of them needs an if in front of it.

1

Make the grid and put the walls on its edges

Create an n × n grid of zeros, set top = left = 0 and bottom = right = n - 1, and start val at 1. Loop while top <= bottom; in a square, left and right meet on the same lap, so this one test covers both.

2

Write the top row, then the right column

Walk the top row left to right, writing val and adding 1 each time, then move top down. Walk the right column from the new top down to bottom, then move right in. Starting at the new top keeps the corner from being written twice.

3

Write the bottom row, then the left column

Walk the bottom row from right back to left, move bottom up, then walk the left column from bottom up to top and move left in. No if is needed: on a final single-cell lap all three of the right, bottom and left loops have empty ranges, and on a final 2 × 2 lap only the left loop does.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def generateMatrix(self, n):
▶3 grid = [[0] * n for _ in range(n)]
▶4 top, bottom, left, right = 0, n - 1, 0, n - 1
▶5 val = 1
▶6 while top <= bottom:
▶7 for c in range(left, right + 1):
▶8 grid[top][c] = val
▶9 val += 1
▶10 top += 1
▶11 for r in range(top, bottom + 1):
▶12 grid[r][right] = val
▶13 val += 1
▶14 right -= 1
▶15 for c in range(right, left - 1, -1):
▶16 grid[bottom][c] = val
▶17 val += 1
▶18 bottom -= 1
▶19 for r in range(bottom, top - 1, -1):
▶20 grid[r][left] = val
▶21 val += 1
▶22 left += 1
▶23 return grid
next value1filled0 of 9 cellsring1 of 2empty 3 × 3 grid, start at 1
val1next number to write
wallstop 0, bottom 2, left 0, right 2
Make a 3 × 3 grid of zeros and put the walls on its edges. A square grid peels into 2 rings, outlined here; each lap of the loop fills one of them.
1next value2filled1 of 9 cellsring1 of 2write 1 → top row, left to right
val2next number to write
wallstop 0, bottom 2, left 0, right 2
Write 1 into row 0, column 0, then count up to 2. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
12next value3filled2 of 9 cellsring1 of 2write 2 → top row, left to right
val3next number to write
wallstop 0, bottom 2, left 0, right 2
Write 2 into row 0, column 1, then count up to 3. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
123next value4filled3 of 9 cellsring1 of 2write 3 → top row, left to right
val4next number to write
wallstop 0, bottom 2, left 0, right 2
Write 3 into row 0, column 2, then count up to 4. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
1234next value5filled4 of 9 cellsring1 of 2write 4 → right column, downward
val5next number to write
wallstop 1, bottom 2, left 0, right 2
Write 4 into row 1, column 2, then count up to 5. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
12345next value6filled5 of 9 cellsring1 of 2write 5 → right column, downward
val6next number to write
wallstop 1, bottom 2, left 0, right 2
Write 5 into row 2, column 2, then count up to 6. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
123465next value7filled6 of 9 cellsring1 of 2write 6 → bottom row, right to left
val7next number to write
wallstop 1, bottom 2, left 0, right 1
Write 6 into row 2, column 1, then count up to 7. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
1234765next value8filled7 of 9 cellsring1 of 2write 7 → bottom row, right to left
val8next number to write
wallstop 1, bottom 2, left 0, right 1
Write 7 into row 2, column 0, then count up to 8. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
12384765next value9filled8 of 9 cellsring1 of 2write 8 → left column, upward
val9next number to write
wallstop 1, bottom 1, left 0, right 1
Write 8 into row 1, column 0, then count up to 9. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
123894765next value10filled9 of 9 cellsring2 of 2write 9 → top row, left to right
val10next number to write
wallstop 1, bottom 1, left 1, right 1
Write 9 into row 1, column 1, then count up to 10. The counter only ever goes up, so the numbers come out in spiral order as long as each cell is visited once.
123894765next value10filled9 of 9 cellsring2 of 2other 3 walks have empty ranges → write nothing
val10next number to write
wallstop 2, bottom 0, left 2, right 0
This ring is the single centre cell, filled by the top walk. The right, bottom and left loops then have empty ranges, because each wall has already passed its partner, so they write nothing. That is why this square version needs no extra checks inside the lap.
123894765next value10filled9 of 9 cellsring2 of 2counter reached 10 → every cell written
val10next number to write
wallstop 2, bottom 0, left 2, right 0
The walls have crossed and the counter stands at 10, one past n² = 9, so every cell was written exactly once. Return the grid.
05

Write and turn when blocked

The grid starts full of zeros, and every written cell holds a number from 1 up, so a non-zero cell is a wall the walk has built itself. dr and dc list the moves right, down, left, up; after each write, look one step ahead and turn clockwise if that cell is off the grid or already filled.

▶1class Solution:
▶2 def generateMatrix(self, n):
▶3 grid = [[0] * n for _ in range(n)]
▶4 dr, dc = [0, 1, 0, -1], [1, 0, -1, 0]
▶5 r = c = d = 0
▶6 for val in range(1, n * n + 1):
▶7 grid[r][c] = val
▶8 nr, nc = r + dr[d], c + dc[d]
▶9 if not (0 <= nr < n and 0 <= nc < n) or grid[nr][nc]:
▶10 d = (d + 1) % 4
▶11 nr, nc = r + dr[d], c + dc[d]
▶12 r, c = nr, nc
▶13 return grid
06

Common pitfalls

Building the rows with list multiplication

✗ Wrong
grid = [[0] * n] * n
✓ Right
grid = [[0] * n for _ in range(n)]

Multiplying the outer list copies one row object n times, so writing to any row writes to all of them. For n = 2 the result is [[4, 3], [4, 3]] instead of [[1, 2], [4, 3]].

Turning only at the edge of the grid

✗ Wrong
if not (0 <= nr < n and 0 <= nc < n):
    d = (d + 1) % 4
✓ Right
if not (0 <= nr < n and 0 <= nc < n) or grid[nr][nc]:
    d = (d + 1) % 4

In the turn-when-blocked version, a filled cell must also force a turn. With only the edge test, n = 3 walks round the outer ring a second time: 9 lands on top of 1 and the centre stays 0, giving [[9, 2, 3], [8, 0, 4], [7, 6, 5]].

07

Edge cases

n = 1

The top-row loop writes 1 into the only cell. The other three loops have empty ranges, the walls cross, and the answer is [[1]].

08

Complexity

Time
O(n²)
Space
O(1)
Each of the n² cells is written exactly once, with a constant amount of loop work per lap on top. Apart from the grid that is returned, only the four walls and the counter are stored.
09

Spiral Matrix II FAQ

Is there a formula for the number in row i, column j?

Yes. The cell sits on ring k = min(i, j, n - 1 - i, n - 1 - j), and the rings outside it hold 4k(n - k) numbers. Add the cell's position along its own ring, counted clockwise from that ring's top-left corner, plus 1. This answers one cell in O(1) without building the grid.

How do you make the spiral start from the centre instead?

Fill the grid as usual, then replace every value v with n² + 1 - v. The largest number ends up in the top-left corner and 1 lands on the last cell of the clockwise walk, so reading upwards from 1 traces the spiral outward, counter-clockwise.