Back to Practice
#0218
Spiral Number Matrix
HardPython35 min25 XP
Problem
Return an n by n spiral number pattern as a list of integer rows.
Why This Matters
Spiral problems test boundary management, a common source of off-by-one errors in matrix code.
Function Signature
def spiral_matrix(n):
Examples
Example 1
Inputn = 3
Output[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
The numbers move right, down, left, and up while the boundaries shrink.
Constraints
- Return the exact requested value.
- Handle small edge cases cleanly.
- Prefer readable Python over clever shortcuts.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputn = 3
Expected[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
The numbers move right, down, left, and up while the boundaries shrink.
Hidden Test Categories
n = 1n = 2n = 4