mediumArrayMatrixArrays & Hashing

Spiral Matrix

mediumTime: O(m * n)Space: O(1)

Signals to notice

traverse matrix in spiral orderlayer by layerboundary tracking

Brute force first

No simpler alternative — spiral traversal IS the approach. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Track four boundaries (top, bottom, left, right), shrink inward after each pass. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

Process one full ring (top row → right column → bottom row → left column), then shrink. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Not checking if the boundary has collapsed after each direction — causes duplicate elements. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern