2dbi

Spiral Matrix

viaLeetCode

Problem Return all elements of an m x n matrix in clockwise spiral order.

Input / Output

  • Input: int matrix. Output: flat list in spiral order.

Constraints

  • m, n up to 10; but clean boundary logic is the entire test — off-by-ones are the failure mode.

Example

  • [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]; non-square [[1,2,3,4],[5,6,7,8],[9,10,11,12]] → [1,2,3,4,8,12,11,10,9,5,6,7].

Expected approach

  • Four boundary pointers (top, bottom, left, right): emit top row → right column → bottom row (guard top <= bottom) → left column (guard left <= right), shrinking each boundary after its pass. The two guards prevent double-emitting on single-row/column remainders — the classic bug. O(m*n)/O(1). Variants: Spiral Matrix II (fill 1..n² spirally), counter-clockwise, starting layer k.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account