#59

Spiral Matrix II

Medium Shrinking boundaries

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Build an n × n matrix filled with 1 to n² in clockwise spiral order.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: fill 1..n² in spiral order.

Why this works: the same four shrinking walls, writing a counter instead of reading.

Example: n = 3

1 2 38 9 47 6 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Off-by-one on the boundaries leading to overwriting cells already filled.

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(1) besides the output.
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon