Spiral Matrix II
Build an n x n matrix filled with 1 to n squared laid out in clockwise spiral order.
Open on LeetCode ↗Intuition
This is Spiral Matrix with the arrows reversed, and it carries the same boundary bug with one nasty difference: here the bug is silent. In problem 54 a missing guard duplicates a value in the output list and you see it immediately. Here the sweeps write instead of read, so a wall you sweep twice simply overwrites a cell you already filled, and the finished grid still looks like a perfectly reasonable spiral. Nothing throws, nothing looks ragged, and a value is quietly missing while another appears twice. So do not trust the picture, trust the counter: check top <= bottom before the bottom sweep and left <= right before the left sweep, and then verify that the running value ends at exactly n squared plus one. The invariant is that the rectangle inside the four walls holds precisely the cells still unwritten, which is why writing into it can never destroy anything.
Approach
Allocate first, then walk the walls
Create the n x n grid of zeros up front. Unlike problem 54 there is no input to read, only positions to visit, so the four-boundary walk is purely a coordinate generator. Keep a single counter val starting at 1 and write val then increment it at every cell the walk touches.
Four sweeps, each retracting its own wall
Fill the top row left-to-right and raise top; the right column top-to-bottom and pull right in; the bottom row right-to-left and raise bottom; the left column bottom-to-top and push left in. Because the counter is monotonic, correctness reduces to visiting every cell exactly once, in the right order.
Guard the return sweeps, then count
Re-check top <= bottom before the bottom sweep and left <= right before the left sweep, exactly as in problem 54. Then use the counter as a self-test: after the loop, val must equal n squared plus one. If a guard were missing the walk would write more cells than the grid has, and that arithmetic catches the silent overwrite that your eyes will not.
Solution & live demo
Edge cases
The top sweep writes the only cell, then both guards fail and the loop exits with val = 2.
The while condition is false immediately and an empty list is returned.
The centre cell is a 1x1 remainder reached by the top sweep alone; the guards stop the return sweeps rewriting it.
The innermost ring is a genuine 2x2, so all four sweeps run on it and no guard fires.