TRT
Sign in
mediumFoundationsLeetCode#boundaries#simulation

Spiral matrix

Return the elements of an m × n matrix in clockwise spiral order, keeping four boundaries straight.

The Runtime Theory Team1 min read
Taught inIndex arithmeticAn array index is an offset into a block of memory. The same arithmetic flattens grids, finds neighbors, wraps around the end and turns a position back into a row and column.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inmatrix = [[1,2,3],[4,5,6],[7,8,9]]

out[1,2,3,6,9,8,7,4,5]

inmatrix = [[1,2,3,4]]

out[1,2,3,4]

inmatrix = [[1],[2],[3]]

out[1,2,3]

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

  1. Walk the top row from left to right, then increase top.
  2. Walk the right column from top to bottom, then decrease right.
  3. Only walk the bottom row if top <= bottom still holds, and only walk the left column if left <= right still holds. Otherwise a single remaining row or column is visited twice.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save