Skip to main content
LeetCode 59, Medium. Topics: Array, Matrix, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

Problem

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

Examples

<img alt="" src=“https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg” style=“width: 242px; height: 242px;” />

Constraints

  • 1 <= n <= 20

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026