15% off all plans & roadmaps Use code
See plansLeetCode 59 · Solution & editorial
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Spiral Matrix II is a Array/Matrix Manipulation Patterns problem, in the Spiral Traversal subpattern. The pattern covers in-place operations, hashing, prefix sums, spiral traversal, and cyclic sort
Master spiral traversal pattern for 2D matrices. Learn to traverse matrices in spiral order for interview problems.
The reference solution runs in O(n^2) time and O(1) space.
Spiral Matrix II has been reported in interviews at Microsoft.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Spiral Matrix II is a Array/Matrix Manipulation Patterns problem, in the Spiral Traversal subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.