Problem overview
The method spiralOrder receives a matrix with m rows and n columns, a list of rows of integers, and returns a list with every element in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row, down the right column, back along the bottom row and up the left column. Then it repeats on what is left inside, until every element has been visited exactly once.
For this matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]. The outer ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 remains in the middle. The required time is O(m * n), since each element is visited once.
Approach: four boundaries that move inward
Tracking the direction and turning at the edges is one way to do it, but it needs a record of which cells were visited. A simpler idea is to track the part of the matrix that has not been visited yet with four numbers: top and bottom (the first and last unvisited rows) and left and right (the first and last unvisited columns).
Each lap of a while loop walks once around that rectangle. After each side is read, the boundary beside it moves one step inward: after the top row, top goes down by one; after the right column, right goes left by one; and so on. When the boundaries cross, nothing is left.
The only delicate point is a rectangle that is thinner than a full ring. If a single row is left, the walk along the top already read it, and walking back along the bottom would read it a second time. The same holds for a single column. That is why the bottom row and the left column are guarded by an if.
On the 3 by 4 example, the first lap reads 1, 2, 3, 4, then 8, 12, then 11, 10, 9, then 5. What is left is a single row, 6 and 7. The second lap reads it from left to right, and the guards stop it from reading it again on the way back.
Step by step
- Start an empty list,
result, to collect the elements in the order they are visited. - Set the row boundaries:
topis 0 andbottomis the last row's index,len(matrix) - 1. - Set the column boundaries:
leftis 0 andrightislen(matrix[0]) - 1. Every row has the same length, so the first row tells how many columns there are. - Loop while both pairs of boundaries have not crossed:
top <= bottomandleft <= right. - Walk the top row from
lefttorightwithrange(left, right + 1), appendingmatrix[top][col]. - Move
topdown. This also stops the top-right corner from being read again by the next walk. - Walk the right column from the new
toptobottom, appendingmatrix[row][right]. - Move
rightone column left. - Check
top <= bottombefore the bottom row. If the top walk used up the last row,tophas passedbottomand there is no bottom row left to read. - Walk the bottom row backwards with
range(right, left - 1, -1)and movebottomup. The stop value is left out, soleft - 1makesleftthe last column read. - Check
left <= rightbefore the left column. A single column leavesrightbelowleftafter its walk down. - Walk the left column upwards with
range(bottom, top - 1, -1)and moveleftone column right. That ends the lap, and the loop condition decides whether another one is needed. - Return
result.
The solution in Python
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
The Python details that matter here:
- Tuple assignment such as
top, bottom = 0, len(matrix) - 1sets two variables in one line. rangeexcludes its stop value. That is why the forward walks end atright + 1andbottom + 1, and the backward walks end atleft - 1andtop - 1.- A
rangecan be empty, and the loop then runs zero times. Whentopmoves pastbottom,range(top, bottom + 1)is empty, so the right-column walk is safely skipped. The twoifchecks are needed for the backward walks, since a backwardrangethat is not empty would still produce elements. - Indexing is
matrix[row][column]. The row comes first, so the top walk usesmatrix[top][col]and the right walk usesmatrix[row][right].
Complexity
Time: O(m * n). Each element is appended exactly once, and the loops do constant work per element, apart from a few boundary updates per lap.
Space: O(1) beyond the output. The method keeps four boundary numbers and loop variables. The returned list holds m * n elements.
Edge cases and common mistakes
- A single column.
[[3], [2], [1]]gives[3, 2, 1]. The top walk reads 3, the right walk reads 2 and 1, and the guards skip the bottom row and the left column. - A single row.
[[1, 2, 3]]gives[1, 2, 3]. The top walk reads everything, and thetop <= bottomguard keeps the backward walk from repeating it. - A 2 by 2 matrix.
[[1, 2], [3, 4]]gives[1, 2, 4, 3]: one lap reads everything. - Missing guards. Without the two
ifchecks, a leftover row or column is read twice, so the result is longer thanm * n. - Moving a boundary too late. If
topis not moved before the right-column walk, the top-right corner is read twice. - Mixing up the stop values. A forward
rangeneeds+ 1on its end, and a backward one needs- 1. Forgetting either one skips the last element of that side.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives[1, 2, 3, 6, 9, 8, 7, 4, 5].[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]gives[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].[[3], [2], [1]]gives[3, 2, 1].[[1, 2, 3]]gives[1, 2, 3].[[1, 2], [3, 4]]gives[1, 2, 4, 3].
