EasyNo. 0867

Transpose Matrix — LeetCode 867 Python Solution

Topics
Array, Matrix, Simulation
Reading time
2 min

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

Example

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

Python solution

PythonSolution
class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        return list(zip(*matrix))

Complexity

Time
O(m × n)where m and n are the number of rows and columns in the matrix matrix, respectively
Space · auxiliary
O(1)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 867. Transpose Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0054Spiral MatrixMedium
0059Spiral Matrix IIMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy
0885Spiral Matrix IIIMedium

Frequently asked questions

How hard is LeetCode 867. Transpose Matrix?

LeetCode 867. Transpose Matrix is rated Easy on LeetCode.

What is the time complexity of LeetCode 867. Transpose Matrix?

The Python solution on this page runs in O(m × n), where m and n are the number of rows and columns in the matrix \textit{matrix}, respectively.

What is the space complexity of LeetCode 867. Transpose Matrix?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 867. Transpose Matrix cover?

LeetCode 867. Transpose Matrix is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.