#54
Spiral Matrix
Medium Shrinking boundaries
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return all elements of an m × n matrix in clockwise spiral order.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: read the matrix around the edges, inward.
Why this works: four walls (top, bottom, left, right) shrink after each side is read.
Example: [[1,2,3],[4,5,6],[7,8,9]]
top row 1 2 3, right col 6 9bottom row 8 7, left col 4middle 5 → [1,2,3,6,9,8,7,4,5]
✦Hints open one at a time
Keep four boundaries: top, bottom, left, right.
Walk right, down, left, up, shrinking the matching boundary after each side.
Check the boundaries again before walking left and up — a single row or column remains in the middle.
↗Approach
Loop while top <= bottom and left <= right: top row, right column, bottom row (if top <= bottom), left column (if left <= right).
</>Solution (Java)
import java.util.*;
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) res.add(matrix[top][c]);
top++;
for (int r = top; r <= bottom; r++) res.add(matrix[r][right]);
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) res.add(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) res.add(matrix[r][left]);
left++;
}
}
return res;
}
}
!Common mistake
Not re-checking boundaries before the bottom row and left column, which prints the middle row or column twice.
Complexity
- Time: O(m·n).
- Space: O(1) besides the output.
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon