Spiral Matrix
Return the elements of a matrix in spiral order.
Return the elements of the matrix in spiral order. The heart of the problem is careful boundary management, not a tricky algorithm.
Pattern fit
This problem is really about shrinking four moving boundaries in a disciplined order, which makes it a good fit for pointer-style boundary control even though it looks like a pure simulation.
Key observation
After traversing one side, you must immediately tighten the corresponding boundary before moving to the next side, otherwise elements get duplicated or skipped.
Target complexity
O(mn) / O(1)
How to break down the solution cleanly
Track four boundaries: top, bottom, left, and right.
Traverse the top row, right column, bottom row, and left column in order.
After finishing each side, shrink the corresponding boundary.
Before traversing the bottom row or left column, re-check whether boundaries still overlap.
Walk through one example
Example: [[1,2,3],[4,5,6],[7,8,9]].
Read top row -> 1,2,3; then right column -> 6,9.
Read bottom row in reverse -> 8,7; then left column upward -> 4.
The remaining center is 5, so final order is [1,2,3,6,9,8,7,4,5].
Reference implementation
Pythondef spiralOrder(matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
order = []
while top <= bottom and left <= right:
for col in range(right - left + 1):
order.append(matrix[top][left + col])
top += 1
for row in range(top, bottom + 1):
order.append(matrix[row][right])
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
order.append(matrix[bottom][col])
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
order.append(matrix[row][left])
left += 1
return order
Common pitfalls
Forgetting to re-check boundary validity before traversing the bottom row or left column.
Updating boundaries in the wrong order and revisiting cells.
Common follow-ups
How would you generate a spiral matrix instead of reading one?
What changes if the matrix is jagged or streamed row by row?
Continue with related problems
Build repeatable depth inside the Two Pointers cluster before moving on.