Wind Numbers Into a Spiral
MediumMatrix
Problem
A ticket printer lays out numbered tickets on a square board of size × size slots. It places ticket 1 in the top-left slot and continues clockwise in a spiral towards the centre: along the top row, down the right column, back along the bottom row, up the left column, and so on, until ticket size² is placed.
Return the filled board.
Example 1
- Input:
- size = 3
- Output:
- [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
1–3 go along the top, 4–5 down the right, 6–7 along the bottom, 8 up the left and 9 in the centre.
Example 2
- Input:
- size = 1
- Output:
- [[1]]
Constraints
- 1 ≤ size ≤ 300
Hint
Show the first hint
This is the spiral readout run backwards: instead of reading cells in spiral order, you write the next number into them.
Walkthrough
How to approach it
01Clarify before coding
- Clockwise starting to the right? Yes, from the top-left slot.
- Is the board always square? Yes, size × size.
- Is size = 1 allowed? Yes, the board is [[1]].
02Brute force
Simulate a walker with a direction vector that turns right whenever the next slot is outside the board or already filled (non-zero).
Cost: O(size²) time and no extra memory beyond the board, since filled slots act as visited flags. This is a perfectly good answer; the boundary version avoids the per-step look-ahead.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.