InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Spiral Matrix

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug