> ## 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.

# Transpose Matrix Python Solution with Tests

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

LeetCode 867, [Easy](https://leetcode-py.wisl.dev/catalog/easy.md). Topics: [Array](https://leetcode-py.wisl.dev/catalog/topics/array), [Matrix](https://leetcode-py.wisl.dev/catalog/topics/matrix), [Simulation](https://leetcode-py.wisl.dev/catalog/topics/simulation). [View on LeetCode](https://leetcode.com/problems/transpose-matrix/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](https://leetcode-py.wisl.dev/practice/testing.md), and a playground notebook:

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

## Problem

Given a 2D integer array `matrix`, return *the **transpose** of* `matrix`.

The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

### Examples

![Transpose hint](https://assets.leetcode.com/uploads/2021/02/10/hint_transpose.png)

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

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

### Constraints

* m == matrix.length
* n == matrix\[i].length
* 1 \<= m, n \<= 1000
* 1 \<= m \* n \<= 10^5
* -10^9 \<= matrix\[i]\[j] \<= 10^9

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(m * n)
    # Space: O(m * n)
    def transpose(self, matrix: list[list[int]]) -> list[list[int]]:
        rows = len(matrix)
        cols = len(matrix[0])
        return [[matrix[row][col] for row in range(rows)] for col in range(cols)]
```

## Complexity

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

## Tags

[NeetCode 250](https://leetcode-py.wisl.dev/catalog/neetcode-250.md), [NeetCode All](https://leetcode-py.wisl.dev/catalog/neetcode.md).


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