Matrix Spiral Traversal - Problem

Given an m x n matrix, return all elements of the matrix in spiral order (clockwise from outside to inside).

The spiral traversal should start from the top-left corner and move in the following pattern:

  • Move right across the top row
  • Move down the right column
  • Move left across the bottom row
  • Move up the left column
  • Repeat for inner layers until all elements are visited

Return the elements as a list/array in the order they were visited.

Input & Output

Example 1 — Basic 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 top-left, go right (1→2→3), down (6→9), left (8→7), up (4), then center (5)
Example 2 — Single Row Matrix
$ Input: matrix = [[1,2,3,4]]
Output: [1,2,3,4]
💡 Note: Single row: traverse left to right, no spiral needed
Example 3 — Single Column Matrix
$ Input: matrix = [[1],[2],[3]]
Output: [1,2,3]
💡 Note: Single column: traverse top to bottom, no horizontal movement

Constraints

  • 1 ≤ m, n ≤ 10
  • -100 ≤ matrix[i][j] ≤ 100

Visualization

Tap to expand
Matrix Spiral TraversalINPUT MATRIXALGORITHM STEPSFINAL RESULT1234567893x3 MatrixStart: Top-left corner1Traverse TOP row2Traverse RIGHT column3Traverse BOTTOM row4Traverse LEFT columnBoundary Shrinking:• top++, right--, bottom--, left++• Process inner layers• Continue until boundaries meetSpiral Result Array[1,2,3,6,9,8,7,4,5]Order: Clockwise spiralfrom outside to insideKey Insight:Instead of tracking visited cells, shrink boundaries after completing each rectangle sideTutorialsPoint - Matrix Spiral Traversal | Optimal Boundary Shrinking
Asked in
Google 35 Amazon 42 Microsoft 28 Apple 15
53.8K Views
High Frequency
~15 min Avg. Time
2.2K 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