> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Spiral Matrix II Python Solution with Tests

> Tested Python solution for LeetCode 59 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 59, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Matrix](/catalog/topics/matrix), [Simulation](/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/spiral-matrix-ii/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 59   # by problem number
lcpy gen -s spiral_matrix_ii   # by problem name
```

## 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](https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg)" style="width: 242px; height: 242px;" />

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

```
Input: n = 1
Output: [[1]]
```

### Constraints

* 1 \<= n \<= 20

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/spiral_matrix_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/spiral_matrix_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2)
    # Space: O(1) excluding the output matrix
    def generate_matrix(self, n: int) -> list[list[int]]:
        matrix = [[0] * n for _ in range(n)]
        top, bottom = 0, n - 1
        left, right = 0, n - 1
        value = 1

        while top <= bottom and left <= right:
            # Move right along the top row
            for col in range(left, right + 1):
                matrix[top][col] = value
                value += 1
            top += 1

            # Move down along the right column
            for row in range(top, bottom + 1):
                matrix[row][right] = value
                value += 1
            right -= 1

            # Move left along the bottom row
            if top <= bottom:
                for col in range(right, left - 1, -1):
                    matrix[bottom][col] = value
                    value += 1
                bottom -= 1

            # Move up along the left column
            if left <= right:
                for row in range(bottom, top - 1, -1):
                    matrix[row][left] = value
                    value += 1
                left += 1

        return matrix
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) | O(1) excluding the output matrix |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.