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 - Boundary Shrinking INPUT 3x3 Matrix 1 2 3 4 5 6 7 8 9 Input: [[1,2,3],[4,5,6],[7,8,9]] ALGORITHM STEPS 1 Initialize Boundaries top=0, bottom=2 left=0, right=2 2 Traverse Right left to right on top row then top++ 3 Traverse Down top to bottom on right col then right-- 4 Traverse Left + Up bottom row: right to left left col: bottom to top Shrink boundaries after each pass FINAL RESULT Spiral Traversal Order 1 [1st] 2 [2nd] 3 [3rd] 4 [8th] 5 [9th] 6 [4th] 7 [7th] 8 [6th] 9 [5th] Output: [1,2,3,6,9,8,7,4,5] OK - Complete! Key Insight: Use four pointers (top, bottom, left, right) as boundaries. After traversing each direction, shrink the corresponding boundary inward. Continue until boundaries cross. Time: O(m*n), Space: O(1) TutorialsPoint - Spiral Matrix | Boundary Shrinking Approach
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