LC 54
LeetCode 54 · Medium

Spiral Matrix

Return all elements of the matrix in spiral order.

Math → · High frequency · Solve on LeetCode →

Try it

Step through the core mechanic. The simulator below runs the math shape this problem is built on.

Walk the pattern

No dedicated step-through for this one yet. The shape is Math — its pattern page has the interactive walkthrough, the reference implementation, and a five-problem progression that this problem sits inside.

The approach

Maintain four shrinking bounds (top, bottom, left, right). Walk right along top then top++, down the right then right−−, and so on, stopping when the bounds cross.

AspectValue
PatternMath
Recognise it byRead a matrix in spiral order.
Time complexityO(mn)
Space complexityO(1)
DifficultyMedium

Who asks it

Companies known to ask this problem, from public LeetCode company-tag aggregations. A signal of where to expect it, not a guarantee.