#867
Transpose Matrix
Easy Index swap
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return the transpose of a matrix (rows become columns). The matrix may not be square.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: rows become columns.
Why this works: the cell at (r, c) moves to (c, r), so the result is n × m.
Example: [[1,2,3],[4,5,6]]
→ [[1,4],[2,5],[3,6]]✦Hints open one at a time
The result has dimensions n × m.
res[c][r] = matrix[r][c].
↗Approach
Allocate the flipped-size array and copy every cell with swapped indexes.
</>Solution (Java)
class Solution {
public int[][] transpose(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[][] res = new int[n][m];
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++)
res[c][r] = matrix[r][c];
return res;
}
}
!Common mistake
Swapping in place — impossible for non-square matrices.
Complexity
- Time: O(m·n).
- Space: O(m·n) for the output.
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon