Problem Statement
Spiral Matrix
You are given a grid of numbers with m rows and n columns. Start at the top-left corner and walk through the grid in a spiral: go right across the top, down the right side, left across the bottom, up the left side, and keep curling inward like that until you have visited every number. Return all the numbers in the order you visited them.
Signals to notice
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.
Trace it on matrix=[[1,2,3],[4,5,6],[7,8,9]]
init: top=0,bottom=2,left=0,right=2, result=[] top row j=0..2 -> append 1,2,3; top=1. result=[1,2,3] right col i=1..2 -> append 6,9; right=1. result=[1,2,3,6,9] top(1)<=bottom(2): bottom row j=1..0 -> append 8,7; bottom=1. result=[1,2,3,6,9,8,7] left(0)<=right(1): left col i=1..1 -> append 4; left=1. result=[1,2,3,6,9,8,7,4] loop2: top row j=1..1 -> append 5; top=2. right col i=2..1 empty; right=0 boundaries collapsed: top(2)>bottom(1) and left(1)>right(0), both inner checks skip while top(2)<=bottom(1) fails -> exit. return [1,2,3,6,9,8,7,4,5]
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.
Shape of the loop
top, bottom = 0, m-1; left, right = 0, n-1; result = []
while top <= bottom and left <= right:
walk left→right along row top; top += 1
walk top→bottom along col right; right -= 1
if top <= bottom: walk right→left along row bottom; bottom -= 1
if left <= right: walk bottom→top along col left; left += 1
return resultPseudocode only — the full worked solution lives in the Solution tab.
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.