> ## 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 Python Solution with Tests

> Tested Python solution for LeetCode 54 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 54, Medium. Topics: Array, Matrix, Simulation. [View on LeetCode](https://leetcode.com/problems/spiral-matrix/description/).

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

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

## Problem

Given an `m x n` matrix, return all elements of the matrix in spiral order.

### Examples

\<img alt="" src="[https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)" style="width: 242px; height: 242px;" />

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

\<img alt="" src="[https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg)" style="width: 322px; height: 242px;" />

```
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
```

### Constraints

* m == matrix.length
* n == matrix\[i].length
* 1 \<= m, n \<= 10
* -100 \<= matrix\[i]\[j] \<= 100

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(m*n)
    # Space: O(1)
    def spiral_order(self, matrix: list[list[int]]) -> list[int]:
        if not matrix or not matrix[0]:
            return []

        # Check if all rows have same length
        cols = len(matrix[0])
        for row in matrix:
            if len(row) != cols:
                raise ValueError("Invalid matrix: all rows must have same length")

        result = []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, cols - 1

        while top <= bottom and left <= right:
            # Right
            for c in range(left, right + 1):
                result.append(matrix[top][c])
            top += 1

            # Down
            for r in range(top, bottom + 1):
                result.append(matrix[r][right])
            right -= 1

            # Left (if still valid row)
            if top <= bottom:
                for c in range(right, left - 1, -1):
                    result.append(matrix[bottom][c])
                bottom -= 1

            # Up (if still valid column)
            if left <= right:
                for r in range(bottom, top - 1, -1):
                    result.append(matrix[r][left])
                left += 1

        return result
```

## Complexity

| Time    | Space |
| ------- | ----- |
| O(m\*n) | O(1)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
