Spiral Matrix
Problem
Given a grid of integers with m rows and n columns, return all of its elements in clockwise spiral order: start at the top-left corner, walk right along the top row, then down the right column, then left along the bottom row, then up the left column, and continue inward until every cell has been visited exactly once.
- The grid has at most about a dozen rows and columns.
- Cell values are small integers.
Examples
[[2,4,6],[8,10,12],[14,16,18]]→[2,4,6,12,18,16,14,8,10].[[1,2,3,4],[10,11,12,5],[9,8,7,6]]→[1,2,3,4,5,6,7,8,9,10,11,12]. After the outer ring, the inner "ring" is the single row11,12, which must not be read twice.[[9],[8],[7]]→[9,8,7]; a single column has only the "right" and "down" moves, and the "left" and "up" passes must be skipped.
Hints
- Keep four boundaries: top, bottom, left, right. Each full lap reads one row or column along each boundary and then shrinks that boundary.
- Where does the naive loop double-count? Think about what happens when only one row or one column remains in the middle.
- After reading the top row and right column, read the bottom row only if
top <= bottomstill holds, and the left column only ifleft <= rightstill holds.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.