InterviewPrepKit

Home / Coding / Math & Geometry

Spiral Matrix

medium Original β†—
Solving tips
  • Model the frontier with four boundaries top/bottom/left/right and consume one edge at a time, shrinking that boundary inward.
  • Loop while top<=bottom and left<=right; go right along top, down right, left along bottom, up left.
  • Re-check top<=bottom before the bottom row and left<=right before the left column so a lone leftover row/column is not emitted twice.
  • Target O(m*n) time and O(1) extra space beyond the output; the matrix may be rectangular so never reuse one dimension for both.

Problem

Given an m x n matrix, return a flat list of all its elements in spiral order: start at the top-left, go right across the top row, down the right column, left across the bottom row, up the left column, and continue inward until every cell has been visited exactly once.

Examples

  • [[1,2,3],[4,5,6],[7,8,9]] β†’ [1,2,3,6,9,8,7,4,5] β€” around the outer ring clockwise, then the center.
  • [[1,2,3,4],[5,6,7,8],[9,10,11,12]] β†’ [1,2,3,4,8,12,11,10,9,5,6,7] β€” a 3Γ—4 spiral.
  • [[7]] β†’ [7] β€” a single element.

Constraints

  • m == len(matrix), n == len(matrix[0])
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
  • The matrix need not be square β€” handle rectangular shapes and the moment the spiral collapses to a single remaining row or column.

Think about it first

Hint 1 Track four boundaries β€” `top`, `bottom`, `left`, `right`. Walk right along `top`, then down `right`, then left along `bottom`, then up `left`, shrinking the relevant boundary inward after each edge.
Hint 2 After finishing a top row, do `top += 1`; after a right column, `right -= 1`, and so on. Continue while `top <= bottom` and `left <= right`.
Hint 3 For a non-square matrix, the last ring can be a single row or single column. Re-check the boundary condition *between* the horizontal and vertical passes so you don't re-traverse a row or column that was already consumed.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.