Transpose Matrix
The key idea
The transpose flips the matrix over its main diagonal: the value at row
i, column j moves to row j, column i. A matrix with m rows and n columns becomes one with n rows and m columns, so allocate the result with swapped dimensions before copying.Problem
Given a 2-D 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. In other words, the value at row i, column j of the input becomes the value at row j, column i of the result.
If the input has m rows and n columns, the transpose has n rows and m columns.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10001 <= m * n <= 10^5-10^9 <= matrix[i][j] <= 10^9
Examples
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]]
Complexity
Time: O(m*n) Space: O(m*n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Matrix / Grid problems
- Game of LifeMEDIUM
- Island PerimeterEASY
- Rotate ImageMEDIUM
- Search a 2D Matrix IIMEDIUM
- Set Matrix ZeroesMEDIUM
- Spiral MatrixMEDIUM
- Spiral Matrix IIMEDIUM