Transpose Matrix - 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.
In other words, if matrix[i][j] contains some value, then in the transposed matrix, that same value will be at transpose[j][i].
Input & Output
Example 1 — Basic Rectangle Matrix
$
Input:
matrix = [[1,2,3],[4,5,6]]
›
Output:
[[1,4],[2,5],[3,6]]
💡 Note:
The transpose flips over the main diagonal: element at (0,0)=1 stays, (0,1)=2 moves to (1,0), (0,2)=3 moves to (2,0), etc.
Example 2 — Square Matrix
$
Input:
matrix = [[1,2],[3,4]]
›
Output:
[[1,3],[2,4]]
💡 Note:
In a 2×2 matrix: (0,1) and (1,0) elements swap positions while diagonal elements (0,0) and (1,1) remain in place.
Example 3 — Single Row
$
Input:
matrix = [[1,2,3,4]]
›
Output:
[[1],[2],[3],[4]]
💡 Note:
A 1×4 matrix becomes a 4×1 matrix - the row becomes a column.
Constraints
- 1 ≤ matrix.length ≤ 1000
- 1 ≤ matrix[i].length ≤ 1000
- -109 ≤ matrix[i][j] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Original m×n matrix with elements at specific positions
2
Transpose Operation
Flip over main diagonal - rows become columns
3
Output Matrix
New n×m matrix with elements at swapped positions
Key Takeaway
🎯 Key Insight: The transpose operation swaps the row and column indices of every element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code