Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1 Output: [[1]]
Constraints:
1 <= n <= 20Problem Overview: Given an integer n, generate an n x n matrix filled with numbers from 1 to n^2 arranged in spiral order. You start at the top-left corner, move right across the first row, then down the last column, left across the bottom row, and continue spiraling inward until the matrix is filled.
Approach 1: Boundary-Based Spiral Simulation (O(n^2) time, O(1) extra space)
This approach simulates the spiral traversal while filling numbers sequentially. Maintain four boundaries: top, bottom, left, and right. Fill the top row from left to right, increment top. Then fill the right column from top to bottom, decrement right. Continue with the bottom row (right to left) and the left column (bottom to top), shrinking the boundaries after each pass. Each iteration writes values directly into the matrix while incrementing the current number.
The key insight is that every spiral "layer" of the matrix can be processed using these four directional passes. By tightening the boundaries after each pass, the algorithm naturally moves inward to the next layer. Every cell is written exactly once, giving O(n^2) time complexity with only constant extra variables.
This is a classic matrix traversal pattern often used in problems involving spiral order traversal or layered processing. The algorithm relies on simple index manipulation within a 2D array and controlled directional movement, making it a clean example of simulation-based problem solving.
Approach 2: Direction Vector Simulation (O(n^2) time, O(1) extra space)
Another implementation tracks the current direction using vectors such as (0,1), (1,0), (0,-1), and (-1,0) for right, down, left, and up. Start at position (0,0) and place numbers sequentially. Before each step, check whether the next cell would go out of bounds or hit a previously filled cell. If so, rotate to the next direction in the cycle.
This version models the spiral movement explicitly and avoids maintaining four boundaries. The logic is slightly more dynamic but still fills exactly n^2 cells with constant extra memory. Many engineers prefer the boundary method for clarity, while the direction-vector method is useful when implementing generalized grid traversal patterns.
Recommended for interviews: The boundary-based spiral simulation is the expected solution. It shows you understand layered matrix traversal and can control indices carefully. The direction-vector version also works, but interviewers typically prefer the boundary approach because it is easier to reason about and implement without edge-case mistakes.
This approach involves iteratively filling the matrix in a spiral pattern while maintaining boundary limits. We initialize four boundaries: top, bottom, left, and right. Starting with top as 0 and so on, we fill the elements from 1 to n2 within these boundaries:
This process repeats until all numbers are placed in the matrix.
The function generateMatrix initializes a 2D array of size n x n and fills it in spiral order using boundary markers. The loop continues until all elements are filled, adjusting the boundaries as needed after each direction traversal.
Time Complexity: O(n^2), as we iterate through every cell of the matrix.
Space Complexity: O(1) for in-place modification, excluding the space required for the output matrix.
We can directly simulate the process of generating the spiral matrix.
Define a 2D array ans to store the spiral matrix. Use i and j to represent the current row and column indices, and use k to represent the current direction index. dirs represents the mapping between direction indices and directions.
Starting from 1, fill each position in the matrix sequentially. After filling a position, calculate the row and column indices of the next position. If the next position is out of bounds or has already been filled, change the direction and then calculate the row and column indices of the next position.
The time complexity is O(n^2), where n is the side length of the matrix. Ignoring the space consumption of the answer array, the space complexity is O(1).
Python
Java
C++
Go
TypeScript
Rust
JavaScript
| Approach | Complexity |
|---|---|
| Iterative Spiral Filling | Time Complexity: O(n^2), as we iterate through every cell of the matrix. |
| Simulation | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Boundary-Based Spiral Simulation | O(n^2) | O(1) | Best general solution for generating spiral matrices; simple logic with clear boundary updates |
| Direction Vector Simulation | O(n^2) | O(1) | Useful when implementing generalized grid movement or when direction-based traversal is preferred |
Spiral Matrix II | Live Coding with Explanation | Leetcode - 59 • Algorithms Made Easy • 23,965 views views
Watch 9 more video solutions →Practice Spiral Matrix II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor