Return all elements of an m×n matrix in spiral order (right across the top, down the right side, left across the bottom, up the left side, inward). e.g. [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5].
Managing four shrinking boundaries without off-by-one errors — disciplined index bookkeeping.
Track four boundaries — top, bottom, left, right — and peel one layer per loop: traverse top row left→right then top++, right column top→bottom then right--, bottom row right→left then bottom--, left column bottom→top then left++. The two guards that prevent duplicate visits on a non-square or single-row/column matrix: before the bottom-row pass check `top <= bottom`, and before the left-column pass check `left <= right`; otherwise a thin matrix re-reads a row or column. Loop while `top <= bottom && left <= right`. There's no clever trick here — the interview signal is whether you keep the boundaries and the four directions straight and handle the degenerate shapes. The same boundary-shrinking idea generalises to rotate-image and spiral-matrix-II (fill instead of read).
Layer-by-layer or directional walk over a grid → maintain shrinking top/bottom/left/right boundaries.
Time O(m·n) · Space O(1) extra (output aside)