Spiral Matrix - Problem
Given an m x n matrix, return all elements of the matrix in spiral order.
The spiral order means starting from the top-left corner, move right across the top row, then down the right column, then left across the bottom row, then up the left column, and continue this pattern inward until all elements are visited.
Input & Output
Example 1 — 3x3 Matrix
$
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
[1,2,3,6,9,8,7,4,5]
💡 Note:
Start at top-left (1), go right across top row (1,2,3), then down right column (6,9), then left across bottom row (8,7), then up left column (4), finally center (5)
Example 2 — 3x4 Rectangle
$
Input:
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
›
Output:
[1,2,3,4,8,12,11,10,9,5,6,7]
💡 Note:
Top row (1,2,3,4), right column (8,12), bottom row right-to-left (11,10,9), left column bottom-to-top (5), remaining center (6,7)
Example 3 — Single Row
$
Input:
matrix = [[1,2,3,4]]
›
Output:
[1,2,3,4]
💡 Note:
Only one row, so spiral is just left-to-right traversal
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
3x3 matrix with numbers 1-9
2
Spiral Pattern
Traverse: right → down → left → up → center
3
Output Array
Elements in spiral order
Key Takeaway
🎯 Key Insight: Use four boundaries that shrink inward after processing each side of the spiral
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code