Spiral Matrix — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Traverse an m × n matrix in spiral order.” There’s no clever algorithm — just careful boundary management. You shrink your traversal window after each pass (right, down, left, up) and stop when the boundaries cross.
The Problem
Given an m x n matrix, return all elements in spiral order.
Example
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Boundary tracking | Do you track top, bottom, left, right and shrink them? |
| Loop termination | Do you check boundaries before left/up passes? |
| Non-square matrix | Does your solution handle m ≠ n, single row, single column? |
Step 1: The Key Insight
Maintain four boundaries: top, bottom, left, right. After traversing each edge, shrink the corresponding boundary inward. Check boundaries before the left and up passes to handle single-row or single-column remainders.
Python Implementation
def spiralOrder(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 c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return result
Time & Space Complexity
| Aspect | Complexity |
|---|---|
| Time | O(m × n) — every cell visited once |
| Space | O(1) extra (not counting output) |
Common Interview Mistakes
- Not checking boundaries before left/up passes. If only one row remains after the right pass, the left pass duplicates cells.
- Off-by-one in ranges.
range(left, right + 1)for right,range(right, left - 1, -1)for left. - Hardcoding for square matrices. Must handle m ≠ n. Test with 1×4 and 4×1.
What a Strong Candidate Sounds Like
“Four boundary variables: top, bottom, left, right. Each iteration traverses one layer: right, down, left, up. After each pass I shrink the boundary. I guard left/up passes with boundary checks for single-row/column cases. O(m×n) time, O(1) extra space.”
Related Problems to Practice
- Product of Array Except Self — Array traversal discipline.
- Binary Tree Level Order Traversal — Layer-by-layer traversal.
Practice This in a Mock Interview
Start a mock interview for Spiral Matrix on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub