Spiral Matrix

medium

You're given an m x n matrix of integers. Walk it in a spiral — start at the top-left, go right across the top row, then down the right side, then left along the bottom, then up the left side — peeling the matrix like an onion, layer by layer, until every cell is visited.

Return all elements of the matrix in the order you visit them, as a single flat list.

Hints

The problem literally tells you the path — top row, right side, bottom row, left side. Can you just do what it says?
You keep changing direction at the same four moments. What tells you it's time to turn — a wall, an already-seen cell, or a boundary you're tracking?
Track four fences (top, bottom, left, right). Read one edge, then pull that fence inward by one. Loop while the fences haven't crossed.

Common doubts

When the remaining shape is a single row or single column, the first two sweeps already consumed it. The if top <= bottom and if left <= right guards stop you from reading those same cells a second time.
No. m and n are independent (each 1 to 10), so rectangular and even single-row or single-column matrices are valid inputs — test those edge shapes.

Interview follow-ups

It's the same boundary walk in reverse — instead of reading matrix[r][c], you write an incrementing counter into each cell as you sweep the four edges (the "generate a spiral matrix" variant).
You can compute which ring k lands on and its offset along that ring in O(1)-ish math per ring, avoiding a full traversal — a nice arithmetic-vs-simulation trade-off to discuss.

Fun facts

  • The boundary-shrinking idea is the exact same machinery used to rotate an image in place — both peel the matrix ring by ring.
  • Spiral traversal shows up in image processing (spiral scan orders) and in classic puzzles like the Ulam prime spiral.

Asked at

AmazonMicrosoftGoogleAdobeApple
Frequently Sometimes Occasionally
Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Right across the top (1,2,3), down the right (6,9), left along the bottom (8,7), up the left (4), then the lone center (5).
Example 2
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]
Outer ring first (1,2,3,4,8,12,11,10,9,5), then the inner row (6,7).
Constraints

- m == matrix.length - n == matrix[i].length - 1 <= m, n <= 10 - -100 <= matrix[i][j] <= 100

Solve this problem →