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 row and column indices: the value at `matrix[r][c]` moves to `result[c][r]`. An `m x n` matrix becomes an `n x m` matrix.
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 row and column indices: the value at matrix[r][c] moves to result[c][r]. An m x n matrix becomes an n x m matrix.
Example 1:
Input: {"matrix":[[1,2,3],[4,5,6],[7,8,9]]}
Output: [[1,4,7],[2,5,8],[3,6,9]]
Constraints:
m==matrix.length
n==matrix[i].length
1≤m,n≤1000
1≤m⋅n≤105
−109≤matrix[i][j]≤109
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"matrix":[[1,2,3],[4,5,6],[7,8,9]]}
The input is 3 x 3, so the transpose is 3 x 3. Allocate an empty 3 x 3 result; every value at [r][c] will land at [c][r].
[r][c] → [c][r]
matrix (3 x 3)
c0
c1
c2
r0
1
2
3
r1
4
5
6
r2
7
8
9
→
result (3 x 3)
r0
r1
r2
c0
c1
c2
Each colour is one input row. It lands as the same-numbered column of the result. The dashed line is the main diagonal, where r = c and values stay put.