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
Spiral Matrix: Traverse from outside to inside123456789Input MatrixSpiral Order:1. Right: 1 → 2 → 32. Down: 6 → 93. Left: 8 → 74. Up: 45. Center: 5Result: [1,2,3,6,9,8,7,4,5]
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
Asked in
Microsoft 42 Amazon 38 Google 35 Apple 28
277.9K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen