MediumNo. 0059

Spiral Matrix II — LeetCode 59 Python Solution

Topics
Array, Matrix, Simulation
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

PythonSolution
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

Time
O(n2)where n is the side length of the matrix
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0054Spiral MatrixMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy
0867Transpose MatrixEasy
0885Spiral Matrix IIIMedium

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(n2), 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.

Free to download. Check it runs on your machine, then pick a plan.