LeetCode #54 Medium

Spiral Matrix

Spiral Matrix is LeetCode 54 (Medium). Given an m × n matrix, return all of its elements in clockwise spiral order: along the top row, down the right column, back along the bottom row, up the left column, then the same again on the ring inside.

The matrix need not be square, so single rows, single columns and thin leftover strips all occur.

Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
arraymatrixsimulation
Open on LeetCode ↗
02

Intuition

Treat the cells you have not read yet as a rectangle fenced by four walls: top, bottom, left and right. One lap reads each wall in turn and pulls that wall inward by one, so the rectangle loses one ring per lap.

  • What the walls guarantee: the cells between them are exactly the cells not yet output. When the walls cross, every cell has been read once.
  • Why the walls are re-checked mid-lap: the top row and right column can use up the rectangle partway through a lap. The bottom and left walks must first confirm a row or column is still there, or they read cells a second time.
How to spot this pattern

"Visit a grid ring by ring" is a boundary walk with shrinking walls. Spiral Matrix II, Rotate Image and printing a matrix in layers use the same four indices.

03

Approach

Try it first

Before reading on, run your loop by hand on a single row such as [[1, 2, 3]]. Count how many times each value lands in the output. If any value appears twice, find which of the four walks ran when it should not have.

1

Put the walls on the edges

Set top = 0, bottom = m - 1, left = 0, right = n - 1. Loop while top <= bottom and left <= right, because that is exactly when unread cells remain.

2

Read the top row, then lower the top wall

Append matrix[top][left..right] from left to right, then add 1 to top. That row is finished, so moving the wall below it removes it from the rectangle.

3

Read the right column, then pull the right wall in

Append matrix[top..bottom][right] from top to bottom, then subtract 1 from right. Starting at the new top avoids reading the corner the top row already took.

4

Read the bottom row if a row is left

Only when top <= bottom, append matrix[bottom][right..left] from right to left and subtract 1 from bottom. Walking right to left keeps the spiral clockwise.

5

Read the left column if a column is left

Only when left <= right, append matrix[bottom..top][left] from bottom to top and add 1 to left. The next lap then starts on the ring one step inside.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def spiralOrder(self, matrix):
▶3 top, bottom = 0, len(matrix) - 1
▶4 left, right = 0, len(matrix[0]) - 1
▶5 out = []
▶6 while top <= bottom and left <= right:
▶7 for c in range(left, right + 1):
▶8 out.append(matrix[top][c])
▶9 top += 1
▶10 for r in range(top, bottom + 1):
▶11 out.append(matrix[r][right])
▶12 right -= 1
▶13 if top <= bottom:
▶14 for c in range(right, left - 1, -1):
▶15 out.append(matrix[bottom][c])
▶16 bottom -= 1
▶17 if left <= right:
▶18 for r in range(bottom, top - 1, -1):
▶19 out.append(matrix[r][left])
▶20 left += 1
▶21 return out
topbottomleftright123456789101112outputdashed box holds the cells not read yet
wallstop 0, bottom 2, left 0, right 3
output[]0 of 12
The four walls start on the edges of the 3 × 4 matrix. The dashed box between them always holds exactly the cells that have not been output yet, so the spiral is done when the box is empty.
topbottomleftright123456789101112output1read 1 on the top row
wallstop 0, bottom 2, left 0, right 3
output[1]1 of 12
Walking the top wall left to right: 1 joins the output.
topbottomleftright123456789101112output12read 2 on the top row
wallstop 0, bottom 2, left 0, right 3
output[1, 2]2 of 12
Walking the top wall left to right: 2 joins the output.
topbottomleftright123456789101112output123read 3 on the top row
wallstop 0, bottom 2, left 0, right 3
output[1, 2, 3]3 of 12
Walking the top wall left to right: 3 joins the output.
topbottomleftright123456789101112output1234read 4 on the top row
wallstop 0, bottom 2, left 0, right 3
output[1, 2, 3, 4]4 of 12
Walking the top wall left to right: 4 joins the output.
topbottomleftright123456789101112output12348read 8 on the right column
wallstop 1, bottom 2, left 0, right 3
output[1, 2, 3, 4, 8]5 of 12
Walking down the right wall: 8 joins the output.
topbottomleftright123456789101112output1234812read 12 on the right column
wallstop 1, bottom 2, left 0, right 3
output[1, 2, 3, 4, 8, 12]6 of 12
Walking down the right wall: 12 joins the output.
topbottomleftright123456789101112output123481211read 11 on the bottom row
wallstop 1, bottom 2, left 0, right 2
output[1, 2, 3, 4, 8, 12, 11]7 of 12
Walking the bottom wall right to left: 11 joins the output.
topbottomleftright123456789101112output12348121110read 10 on the bottom row
wallstop 1, bottom 2, left 0, right 2
output[1, 2, 3, 4, 8, 12, 11, 10]8 of 12
Walking the bottom wall right to left: 10 joins the output.
topbottomleftright123456789101112output123481211109read 9 on the bottom row
wallstop 1, bottom 2, left 0, right 2
output[1, 2, 3, 4, 8, 12, 11, 10, 9]9 of 12
Walking the bottom wall right to left: 9 joins the output.
top = bottomleftright123456789101112output1234812111095read 5 on the left column
wallstop 1, bottom 1, left 0, right 2
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5]10 of 12
Walking up the left wall: 5 joins the output.
top = bottomleftright123456789101112output12348121110956read 6 on the top row
wallstop 1, bottom 1, left 1, right 2
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6]11 of 12
Walking the top wall left to right: 6 joins the output.
top = bottomleftright123456789101112output123481211109567read 7 on the top row
wallstop 1, bottom 1, left 1, right 2
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]12 of 12
Walking the top wall left to right: 7 joins the output.
bottomtopleftright123456789101112output123481211109567the right column has no cells left → read nothing
wallstop 2, bottom 1, left 1, right 2
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]12 of 12
The top row was the last row in the box, so top has moved below bottom. The right-column loop runs from top to bottom, which is now an empty range, so nothing is read; right still moves in.
bottomtopleft = right123456789101112output123481211109567walls crossed → skip the bottom row
wallstop 2, bottom 1, left 1, right 1
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]12 of 12
top (2) is now below bottom (1), so no row is left. Without this check the loop would walk row 1 again, right to left, and output the red cell a second time. The guard skips it.
bottomtopleft = right123456789101112output123481211109567the left column has no cells left → read nothing
wallstop 2, bottom 1, left 1, right 1
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]12 of 12
No rows are left between top and bottom, so the left-column loop has an empty range and reads nothing. left moves in, and the box is now empty.
bottomtoprightleft123456789101112output123481211109567box empty → return all 12 values
wallstop 2, bottom 1, left 2, right 1
output[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]12 of 12
The walls have crossed, so every cell has been read exactly once. The answer is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
05

Step and turn with a seen grid

dr and dc hold the four moves in clockwise order: right, down, left, up. After reading a cell, look one step ahead. If that cell is off the grid or already in seen, add 1 to d (wrapping with % 4) and step that way instead. The loop runs exactly m * n times, so it never needs to test whether the walk is finished.

▶1class Solution:
▶2 def spiralOrder(self, matrix):
▶3 m, n = len(matrix), len(matrix[0])
▶4 seen = [[False] * n for _ in range(m)]
▶5 dr, dc = [0, 1, 0, -1], [1, 0, -1, 0]
▶6 r = c = d = 0
▶7 out = []
▶8 for _ in range(m * n):
▶9 out.append(matrix[r][c])
▶10 seen[r][c] = True
▶11 nr, nc = r + dr[d], c + dc[d]
▶12 if not (0 <= nr < m and 0 <= nc < n) or seen[nr][nc]:
▶13 d = (d + 1) % 4
▶14 nr, nc = r + dr[d], c + dc[d]
▶15 r, c = nr, nc
▶16 return out
06

Common pitfalls

Checking the walls only at the top of the loop

✗ Wrong
for c in range(right, left - 1, -1):
    out.append(matrix[bottom][c])
bottom -= 1
✓ Right
if top <= bottom:
    for c in range(right, left - 1, -1):
        out.append(matrix[bottom][c])
    bottom -= 1

The while condition was true when the lap began, but the walls have moved since. On [[1, 2, 3]] the unguarded bottom walk reads the same row backwards and returns [1, 2, 3, 2, 1]. On [[1], [2], [3]] an unguarded left walk returns [1, 2, 3, 2].

07

Edge cases

A 1 × 1 matrix

The top walk reads the only cell and moves top past bottom. The right walk has an empty range, both guards fail, and the loop ends with one value.

A single centre cell, as in a 3 × 3 matrix

The inner lap starts with top = bottom = 1 and left = right = 1. The top walk reads the centre cell, and every other walk is either empty or skipped by its guard.

08

Complexity

Time
O(m · n)
Space
O(1)
Each cell is appended exactly once, and the guards and empty ranges add only a few checks per lap. Apart from the output list, only the four wall indices are stored.
09

Spiral Matrix FAQ

How do you read the spiral counter-clockwise instead?

Change the order of the walks: down the left column, along the bottom row left to right, up the right column, then along the top row right to left. The checks move with them: the third and fourth walks are the ones that need left <= right and top <= bottom first.

How is Spiral Matrix II different?

Spiral Matrix II walks the same path but writes the numbers 1 to n² into an empty square grid instead of reading values out. Its grid is always square, which changes which checks it really needs.