Spiral Matrix (LeetCode 54): Solution and Explanation

Medium
Array
Matrix
Simulation

Given an m by n matrix, return all of its elements in spiral order. Start at the top-left corner, travel right along the top row, down the right column, left along the bottom row, up the left column, and keep circling inward until every element has been visited once.

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

Intuition

One approach is to simulate a walker. Keep a direction, step forward, and turn right whenever the next cell is out of bounds or already visited. That works, but it needs an m by n visited grid and some care with turning logic.

A cleaner observation is that the spiral peels the matrix one rectangular ring at a time. After you read the top row, that row is done forever, so the top boundary can move down by one. After the right column, the right boundary moves left. The same goes for the bottom row and left column. Four boundary variables describe the unvisited rectangle at every moment, and no visited grid is needed.

The only tricky part is a matrix that is not square. After reading the top row and the right column, the remaining rectangle may have collapsed to nothing, for example when only a single row or column was left. If you went on to read the bottom row anyway, you would revisit the same cells in reverse. So the code checks the boundaries again in the middle of each lap and stops early when the rectangle is empty.

Approach: Shrinking boundaries simulation

  1. Set left = 0, right = len(matrix[0]), top = 0 and bottom = len(matrix). The right and bottom boundaries are exclusive.
  2. While left < right and top < bottom, read the top row from left to right - 1, then increment top.
  3. Read the right column from top to bottom - 1 at column right - 1, then decrement right.
  4. If the rectangle is now empty, break out of the loop to avoid revisiting cells.
  5. Read the bottom row from right - 1 down to left at row bottom - 1, then decrement bottom.
  6. Read the left column from bottom - 1 up to top at column left, then increment left, and loop again for the next inner ring.

Step-by-step example

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
  1. Read the top row to get 1, 2, 3, 4, and move top to 1.
  2. Read the right column (rows 1 and 2 of column 3) to get 8, 12, and move right to 3.
  3. The rectangle is still non-empty, so read the bottom row right to left to get 11, 10, 9, and move bottom to 2.
  4. Read the left column upward (row 1 of column 0) to get 5, and move left to 1.
  5. On the second lap, the top row is row 1 from column 1 to 2, giving 6, 7, and top becomes 2. The right column has no rows left, right becomes 2, and the mid-loop check sees top equal to bottom, so it stops.
  6. The result is [1,2,3,4,8,12,11,10,9,5,6,7].

Code: Python, Java, C++

1class Solution:
2    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
3        res = []
4        left, right = 0, len(matrix[0])
5        top, bottom = 0, len(matrix)
6        
7        while left < right and top < bottom:
8            # get every i in the top row
9            for i in range(left, right):
10                res.append(matrix[top][i])
11            top += 1
12            
13            # get every i in the right col
14            for i in range(top, bottom):
15                res.append(matrix[i][right - 1])
16            right -= 1
17            
18            if not (left < right and top < bottom):
19                break
20            
21            # get every i in the bottom row
22            for i in range(right - 1, left - 1, -1):
23                res.append(matrix[bottom - 1][i])
24            bottom -= 1
25            
26            # get every i in the left col
27            for i in range(bottom - 1, top - 1, -1):
28                res.append(matrix[i][left])
29            left += 1
30            
31        return res

Time and space complexity

Time

O(m × n)

Every element is appended exactly once, and the boundary bookkeeping adds only constant work per lap.

Space

O(1)

Apart from the output list, which must hold all m × n values, only four boundary variables are used.

Other approaches

Direction vectors with a visited grid (time O(m × n), space O(m × n))

Walk one cell at a time using a list of four direction vectors, turning clockwise when the next cell is out of bounds or already visited. It generalizes easily to other walking patterns but needs an extra m by n grid.

Peel and rotate (time O(m × n × min(m, n)), space O(m × n))

Repeatedly take the first row of the matrix, then rotate the remainder counterclockwise so the next side becomes the first row. It is very short in Python but rebuilds the matrix on every step.

Common mistakes

  • Skipping the mid-loop boundary check, which duplicates elements for single-row or single-column leftovers such as a 3 by 4 matrix.
  • Mixing inclusive and exclusive boundaries. Here right and bottom are exclusive, so the right column is right - 1 and the bottom row is bottom - 1.
  • Updating a boundary before reading its line, which skips the corner cells.
  • Assuming the matrix is square and using a single size variable for both dimensions.

Frequently asked questions

How do you traverse a matrix in spiral order?

Keep four boundaries for the unvisited rectangle. Read the top row, right column, bottom row and left column in turn, shrinking the matching boundary after each, until the rectangle is empty.

Why does the spiral matrix code need a check in the middle of the loop?

After the top row and right column, a non-square matrix may have nothing left. Without the check, the bottom row and left column loops would read cells that were already visited.

What is the time complexity of Spiral Matrix?

It is O(m × n), since each element is visited exactly once. Extra space is O(1) beyond the output.