Browse Curriculum
FAANGPrep Sprint
Medium
Spiral Matrix
Return all elements of the matrix in spiral order.
Problem Understanding
Given an m x n matrix, return all elements of the matrix in spiral order (Right -> Down -> Left -> Up).
Interactive Visualization
Step 1 / 1
Visualization data missing
Initializing...
1x
Watch the path as we peel the matrix layer by layer.
Strategy
We can simulate the spiral movement by defining boundaries (top, bottom, left, right):
- Move Right: Traverse from
lefttoright. Incrementtop. - Move Down: Traverse from
toptobottom. Decrementright. - Move Left: Traverse from
righttoleft. Decrementbottom. (Checktop <= bottomfirst) - Move Up: Traverse from
bottomtotop. Incrementleft. (Checkleft <= rightfirst)
Initialize
top=0,bottom=rows-1,left=0,right=cols-1.Loop while
top <= bottomandleft <= right.
Dry Run
Matrix: [[1,2,3],[4,5,6],[7,8,9]]
| Step | Action | Output After Step | Boundaries Update |
|---|---|---|---|
| 1 | Right | [1, 2, 3] |
top becomes 1 |
| 2 | Down | [..., 6, 9] |
right becomes 1 |
| 3 | Left | [..., 8, 7] |
bottom becomes 1 |
| 4 | Up | [..., 4] |
left becomes 1 |
| 5 | Right | [..., 5] |
top becomes 2. Loop Ends. |
Edge Cases & Common Mistakes
Watch out for:
Single Row/Column: Ensure the inner loops (
leftcheck,topcheck) prevent double-counting.Empty Matrix: Handle gracefully.
Non-Square Matrix: Logic must hold for
m != n.
Complexity Analysis
- Time Complexity: O(M * N). Visit every element once.
- Space Complexity: O(1). Output array doesn't count towards space.
Solution
Simulation with boundaries.
1class Solution:2 def spiralOrder(self, matrix: List[List[int]]) -> List[int]:3 result = []4 if not matrix: return result56 top, bottom = 0, len(matrix) - 17 left, right = 0, len(matrix[0]) - 189 while top <= bottom and left <= right:10 # Move Right11 for i in range(left, right + 1):12 result.append(matrix[top][i])13 top += 11415 # Move Down16 for i in range(top, bottom + 1):17 result.append(matrix[i][right])18 right -= 11920 if top <= bottom:21 # Move Left22 for i in range(right, left - 1, -1):23 result.append(matrix[bottom][i])24 bottom -= 12526 if left <= right:27 # Move Up28 for i in range(bottom, top - 1, -1):29 result.append(matrix[i][left])30 left += 13132 return result
ON THIS PAGE
- Problem Understanding
- Interactive Visualization
- Strategy
- Dry Run
- Edge Cases & Common Mistakes
- Complexity Analysis
- Solution
