Given an m × n matrix, return all of its elements in spiral order: along the top row, down the right column, back along the bottom row, up the left column, then inward.
Before you code
Keep four boundaries: top, bottom, left and right. Each side you walk uses up one boundary. The bugs in this problem are all at the edges, so trace a single row and a single column by hand first.
Hints
- Walk the top row from
lefttoright, then increasetop. - Walk the right column from
toptobottom, then decreaseright. - Only walk the bottom row if
top <= bottomstill holds, and only walk the left column ifleft <= rightstill holds. Otherwise a single remaining row or column is visited twice. - Stop when you have collected m × n elements.
Production & complexity notes
When solving Spiral matrix on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Index arithmetic to reinforce the underlying pattern.
What it practices
Moving through a grid by adjusting row and column indexes, from Index arithmetic.