← Matrix Traversal

Pattern Recognition Drill

#118 — Spiral Matrix

Medium Math & Geometry

The Problem

Given an m×n matrix, return all elements in spiral order.

What approach would you use?

Think about it before scrolling down.

Key Signals

Matrix Traversal

Track 4 boundaries. Traverse right, down, left, up; shrink after each. O(m*n).

Alt: DFS / Recursion

Mark visited cells, turn right when hitting a wall or visited cell. Same O(m*n).

Common Trap

Check boundary conditions after EACH direction — the inner boundaries may have already crossed.

← #117