AlgoInsight

DSA problem

Spiral Matrix II

MediumMatrix (2D Array)Pattern: Matrix Manipulationtop600AmazonMicrosoftGoogleApple

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

Example 1
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Explanation: Fill top row 1,2,3, right column 4,5, bottom row 6,7, left column 8, then the center 9.
Example 2
Input: n = 1
Output: [[1]]
Explanation: A 1x1 matrix holds only the value 1.
Example 3
Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
Explanation: The outer ring is filled 1 through 12, then the inner 2x2 ring is filled 13 through 16 in the same spiral direction.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

matrixarraysimulationtwo-dimensional

Browse all DSA problems