DSA problem
Transpose Matrix
Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is obtained by flipping the matrix over its main diagonal, switching the matrix's row and column indices.
Concretely, if the original matrix has R rows and C columns, the transposed matrix has C rows and R columns, and the element at position (i, j) in the result equals the element at position (j, i) in the original. Unlike an in-place rotation, a transpose of a non-square matrix changes the overall shape, so a fresh result matrix of dimensions C x R is generally required.
The intuition for the optimal approach is direct simulation: allocate a result matrix sized C x R, then iterate over every cell (i, j) of the original and write its value into result[j][i]. This single pass touches each element exactly once, giving linear time in the number of cells. Because the transpose can have different dimensions than the input, building a new array is the cleanest and canonical solution.
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]][[1,4,7],[2,5,8],[3,6,9]]matrix = [[1,2,3],[4,5,6]][[1,4],[2,5],[3,6]]matrix = [[5]][[5]]Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 1000
- 1 <= m * n <= 100000
- -1000000000 <= matrix[i][j] <= 1000000000
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.