Skip to main content

54. Spiral Matrix

medium

Traverse a matrix in spiral order, peeling off concentric rectangles. A classic boundary-tracking problem that punishes off-by-one errors.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an m x n matrix, return all elements of the matrix in spiral order. Spiral order means starting from the top-left, going right, then down the right column, then left along the bottom row, then up the left column, and continuing inward layer by layer until every element has been visited.

Constraints

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

Examples

Example 1

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,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]

Example 3

Input
matrix = [[7]]
Output
[7]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Track four boundaries: top, bottom, left, right. Each spiral layer walks the perimeter of the current bounded region.

Hint 2

After traversing each edge, shrink the corresponding boundary inward. After the top row, increment top. After the right column, decrement right. And so on.

Hint 3

Stop when top > bottom or left > right. Be careful with single-row or single-column residuals — check the boundary condition before walking back along a row that already got consumed.

Solution approach

Reveal approach

Maintain four pointers: top, bottom, left, right, initialized to 0, m-1, 0, n-1. Loop while top <= bottom and left <= right. In each iteration: walk left to right across row top, then increment top. Walk top to bottom down column right, then decrement right. If top <= bottom, walk right to left across row bottom, then decrement bottom (the check prevents double-counting a single remaining row). If left <= right, walk bottom to top up column left, then increment left (same reason). The two guards are the only subtle part; without them an odd-dimensioned matrix re-traces its middle row or column. After the loop the result vector contains all m*n elements in spiral order.

Complexity

Time
O(m * n)
Space
O(1)

Related patterns

  • matrix
  • simulation

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Google
  • Apple
  • Meta

Practice these live with InterviewChamp.AI

Drill Spiral Matrix and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →