Spiral Matrix II – Solution & Complexity
Solution Walkthrough
1. Understand the movement pattern
- The fill direction cycles right, down, left, and up.
- After finishing one side, the active unfilled rectangle becomes smaller.
2. Brute-force with direction vectors and visited cells
- Keep a direction index and turn whenever the next cell would be out of bounds or already filled.
- This is straightforward, but it needs an extra visited-state check on every step.
3. Shrink four boundaries instead of checking visited
- Because the matrix is always square and we fill complete outer rings, we can track just
top,bottom,left, andright. - That avoids a visited check on every move and makes the control flow more interview-friendly.
4. Fill one ring at a time
- Write the top row, right column, bottom row, and left column, then move all four boundaries inward.
- The same loop naturally handles the final center cell for odd
n.
5. Dry run / ring trace
Trace n = 3.
| ring action | matrix state |
|---|---|
| fill top row | [[1,2,3],[0,0,0],[0,0,0]] |
| fill right column | [[1,2,3],[0,0,4],[0,0,5]] |
| fill bottom row backward | [[1,2,3],[0,0,4],[7,6,5]] |
| fill left column upward | [[1,2,3],[8,0,4],[7,6,5]] |
| next inner ring | [[1,2,3],[8,9,4],[7,6,5]] |
6. Common mistakes and follow-ups
- Forgetting to guard the bottom-row and left-column passes after shrinking boundaries.
- Turning direction too early or too late in the visited-matrix approach.
- Off-by-one errors on inclusive boundary loops.
- Follow-up: how would you adapt the same idea to generate an
m x nspiral instead of a square only?
7. Edge cases to test mentally
n = 1should return a single-cell matrix.n = 2is the smallest case that touches all four directions.- Odd
nleaves one center cell, which the same boundary loop fills naturally. - Larger
njust repeats the same ring logic.
8. Final full solution and complexity
Shrink four boundaries while filling one outer ring per loop. Every cell is written exactly once, so time is O(n^2) and the returned matrix uses O(n^2) space.