← All patterns
Matrix / Grid Traversal
Navigate a 2D grid in a specific order (spiral, diagonal, rotation, layer-by-layer) or apply in-place transformations.
When to use it
- Spiral matrix, rotate image 90°, set matrix zeroes.
- Problems requiring careful boundary management and directional iteration.
Signals in the problem statement
- Input is a 2D array/matrix.
- 'Spiral', 'rotate', 'layer', 'diagonal' in the problem statement.
Common pitfalls
- Off-by-one errors in boundary conditions (e.g. spiral loop termination, layer traversal).
- Forgetting to transpose before reversing rows (or vice versa) for 90° rotation.
Practice Problems
Rotate Image
MediumAsked at: Amazon, Apple, Microsoft
Rotate an n x n 2D matrix 90 degrees clockwise in-place.
Time: O(n²) · Space: O(1)
Spiral Matrix
MediumAsked at: Amazon, Google, Microsoft
Given an m x n matrix, return all elements in spiral order (outer layer first, clockwise).
Time: O(m*n) · Space: O(1) ignoring output