Skip to content
Problem 59 · LeetCode 59(opens in a new tab)

Spiral Matrix II

MediumMatrices

You get one whole number, n. Build a square grid with n rows and n columns and write the numbers 1, 2, 3 and so on up to n² into it, following a spiral.

Start in the top-left corner and move right. Each time you would leave the grid or land on a cell that already has a number, turn clockwise. Keep going until every cell is used, and return the grid.

Example 1

Input:  n = 4
Output: [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
Why:    the outer ring takes 1 to 12, the inner 2 × 2 ring takes 13 to 16
1 more example and the constraints

Example 2

Input:  n = 2
Output: [[1, 2], [4, 3]]
Why:    right, down, left, and the grid is full

Constraints

  • 1 ≤ n ≤ 20
  • The grid always holds exactly n² numbers, from 1 to n²

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk and turnO(n²)
  2. Shrinking boundsO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 20Verdict
Walk and turnO(n²)
Passes; turn test is fiddly
Shrinking boundsO(n²)
Best; no lookahead at all

n = the side of the grid, so there are n² cells to fill.

Edge cases to test

  • n = 1. The answer is [[1]]: one lap that writes a single cell.
  • Odd n. The centre cell is a lap of its own, filled by the top-row loop alone.
  • Even n. The last lap is a 2 × 2 ring, so no single centre cell is left.
  • Largest n. n = 20 gives 400 cells; the numbers stay small.

Common mistakes

  • Moving a bound before its side is filled, so the next side starts one cell off.
  • Turning only at the grid edge in the walk version, so the second lap runs over numbers already written.
  • Writing the corner cells twice, once at the end of one side and again at the start of the next.

How to talk through it

  1. 1Clarify. Clockwise from the top-left corner, starting to the right? Can n be 1?
  2. 2Name the walk. Say the rule: go straight, turn clockwise at a wall or a filled cell.
  3. 3Switch to bounds. Four bounds frame the empty part; each side moves one bound inward when done.
  4. 4Code one lap. Four loops, each followed by its bound update. Say why corners are written once.
  5. 5Test out loud. Run n = 1, n = 2 and n = 3 to cover the centre cell and the small ring.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?