Spiral Matrix II — LeetCode 59 Python Solution

MediumArrayMatrixSimulation
Problem
#59
Reading time
2 min

The problem

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example

Input
n = 3
Output
[[1,2,3],[8,9,4],[7,6,5]]

Python solution

Python
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        ans = [[0] * n for _ in range(n)]
        dirs = (0, 1, 0, -1, 0)
        i = j = k = 0
        for v in range(1, n * n + 1):
            ans[i][j] = v
            x, y = i + dirs[k], j + dirs[k + 1]
            if x < 0 or x >= n or y < 0 or y >= n or ans[x][y]:
                k = (k + 1) % 4
            i, j = i + dirs[k], j + dirs[k + 1]
        return ans

Complexity

MeasureComplexity
TimeO(n^2), where n is the side length of the matrix
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 59. Spiral Matrix II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 59. Spiral Matrix II?
LeetCode 59. Spiral Matrix II is rated Medium on LeetCode.
What is the time complexity of LeetCode 59. Spiral Matrix II?
The Python solution on this page runs in O(n^2), where n is the side length of the matrix.
What is the space complexity of LeetCode 59. Spiral Matrix II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 59. Spiral Matrix II cover?
LeetCode 59. Spiral Matrix II is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview