Spiral Matrix (LeetCode 54): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Set
left = 0,right = len(matrix[0]),top = 0andbottom = len(matrix). The right and bottom boundaries are exclusive. - While
left < rightandtop < bottom, read the top row fromlefttoright - 1, then incrementtop. - Read the right column from
toptobottom - 1at columnright - 1, then decrementright. - If the rectangle is now empty, break out of the loop to avoid revisiting cells.
- Read the bottom row from
right - 1down toleftat rowbottom - 1, then decrementbottom. - Read the left column from
bottom - 1up totopat columnleft, then incrementleft, 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]]
- Read the top row to get 1, 2, 3, 4, and move
topto 1. - Read the right column (rows 1 and 2 of column 3) to get 8, 12, and move
rightto 3. - The rectangle is still non-empty, so read the bottom row right to left to get 11, 10, 9, and move
bottomto 2. - Read the left column upward (row 1 of column 0) to get 5, and move
leftto 1. - On the second lap, the top row is row 1 from column 1 to 2, giving 6, 7, and
topbecomes 2. The right column has no rows left,rightbecomes 2, and the mid-loop check seestopequal tobottom, so it stops. - 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 res1class Solution {
2 public List<Integer> spiralOrder(int[][] matrix) {
3 List<Integer> res = new ArrayList<>();
4 int left = 0, right = matrix[0].length;
5 int top = 0, bottom = matrix.length;
6
7 while (left < right && top < bottom) {
8 for (int i = left; i < right; i++) res.add(matrix[top][i]);
9 top++;
10
11 for (int i = top; i < bottom; i++) res.add(matrix[i][right - 1]);
12 right--;
13
14 if (!(left < right && top < bottom)) break;
15
16 for (int i = right - 1; i >= left; i--) res.add(matrix[bottom - 1][i]);
17 bottom--;
18
19 for (int i = bottom - 1; i >= top; i--) res.add(matrix[i][left]);
20 left++;
21 }
22 return res;
23 }
24}1class Solution {
2public:
3 vector<int> spiralOrder(vector<vector<int>>& matrix) {
4 vector<int> res;
5 int left = 0, right = matrix[0].size();
6 int top = 0, bottom = matrix.size();
7
8 while (left < right && top < bottom) {
9 for (int i = left; i < right; i++) res.push_back(matrix[top][i]);
10 top++;
11
12 for (int i = top; i < bottom; i++) res.push_back(matrix[i][right - 1]);
13 right--;
14
15 if (!(left < right && top < bottom)) break;
16
17 for (int i = right - 1; i >= left; i--) res.push_back(matrix[bottom - 1][i]);
18 bottom--;
19
20 for (int i = bottom - 1; i >= top; i--) res.push_back(matrix[i][left]);
21 left++;
22 }
23 return res;
24 }
25};Time and space complexity
O(m × n)
Every element is appended exactly once, and the boundary bookkeeping adds only constant work per lap.
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
rightandbottomare exclusive, so the right column isright - 1and the bottom row isbottom - 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.