DSA problem
Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with the elements from 1 to n * n in spiral order. The number 1 is placed at the top-left corner, and consecutive integers are written along the same spiral path used for reading a matrix outward to inward.
This is the inverse of reading a matrix in spiral order: instead of collecting existing values, you write the running counter 1, 2, 3, ... into successive cells along the spiral. The structural logic is identical, so the same four-boundary technique applies.
The intuition for the optimal approach is to maintain top, bottom, left, and right boundaries and a counter num that starts at 1. Walk the top row, right column, bottom row, and left column in order, writing num into each cell and incrementing it, then shrink the matching boundary. Because the matrix is always square, each layer is complete and the loop naturally terminates once num exceeds n * n. Every cell is written exactly once, yielding quadratic time in n.
Examples
n = 3[[1,2,3],[8,9,4],[7,6,5]]n = 1[[1]]n = 4[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]Constraints
- 1 <= n <= 20
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.