Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #59: Spiral Matrix II

In this guide, we solve Leetcode #59 Spiral Matrix II in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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 <= 20

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Matrix, Simulation

Intuition

Grid problems are easiest when you define clear row/column boundaries.

A consistent traversal order prevents off-by-one errors.

Approach

Iterate by rows, columns, or layers depending on the requirement.

Keep bounds updated as the traversal progresses.

Steps:

  • Define bounds or directions.
  • Visit cells in order.
  • Update result and move bounds.

Example

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

Python Solution

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

The time complexity is O(n2)O(n^2)O(n2), where nnn is the side length of the matrix. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy