Transpose Matrix
Easy · Matrix · Array · Matrix · Simulation
Problem
You are given an integer matrix matrix with m rows and n columns. Return its transpose: a new matrix with n rows and m columns in which the value at row i, column j is the value that was at row j, column i of matrix.
Put another way, row k of the input becomes column k of the output, in the same order. The matrix need not be square, so the shape usually changes.
Examples
Input: matrix = [[5,8,1],[2,0,7]] Output: [[5,2],[8,0],[1,7]]
The 2 × 3 input becomes 3 × 2: the first row [5,8,1] is now the first column.
Input: matrix = [[4,-3],[6,9]] Output: [[4,6],[-3,9]]
For a square matrix only the values off the diagonal move: -3 and 6 trade places.
Input: matrix = [[7]] Output: [[7]]
A single cell is its own transpose.
Constraints
- m == len(matrix), n == len(matrix[i])
- 1 <= m, n <= 1000
- 1 <= m · n <= 10^5
- -10^9 <= matrix[i][j] <= 10^9
Approaches
- Collect each column by scanning every cell — time O(m · n²), space O(m · n)
Follow-up
For a square matrix you can transpose in place by swapping matrix[i][j] with matrix[j][i] for every j > i; that is the first half of rotating an image by 90 degrees. For a rectangular matrix stored as one flat array, in-place transposition is possible too, by following the cycles of the index map k → k · m mod (m · n - 1), but it is far trickier.
Related problems
Start free on Cariara · Coding problems · System design studio