Transpose of a Matrix
Solve this Problemmatrix, return its transpose — the matrix formed by reflecting every element across the main diagonal, so that result[j][i] = matrix[i][j] for every cell. Rows become columns and columns become rows.
Copying into a brand new matrix always works, but a square matrix has a trick a rectangular one doesn't: since the transposed matrix has exactly the same dimensions as the original, every cell above the main diagonal can simply trade places with its mirror below it, transposing the whole matrix in place with no extra memory at all.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ n ≤ 50 - ◆
-1000 ≤ matrix[i][j] ≤ 1000 - ◆
matrix is square (n × n)
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int[][] transposeMatrix(int[][] matrix) { |
| 3 | int n = matrix.length; |
| 4 | for (int i = 0; i < n; i++) { |
| 5 | for (int j = i + 1; j < n; j++) { |
| 6 | int temp = matrix[i][j]; |
| 7 | matrix[i][j] = matrix[j][i]; |
| 8 | matrix[j][i] = temp; |
| 9 | } |
| 10 | } |
| 11 | return matrix; |
| 12 | } |
| 13 | } |
| 14 |
3Transpose in place: swap matrix[i][j] with matrix[j][i] for every pair above the main diagonal — no new matrix needed.
Approach & Solutions
Brute Force — Extra Matrix
BruteAllocate a brand new n×n matrix, and copy every cell of the original into its transposed position: matrix[i][j] goes to result[j][i]. Correct and works for any matrix shape, but the extra matrix costs O(n²) memory that a square matrix doesn't actually need.
O(n²)O(n²)1class Solution {
2 public int[][] transposeMatrix(int[][] matrix) {
3 int n = matrix.length;
4 int[][] result = new int[n][n];
5 for (int i = 0; i < n; i++) {
6 for (int j = 0; j < n; j++) {
7 result[j][i] = matrix[i][j];
8 }
9 }
10 return result;
11 }
12}Optimal — In-Place Swap
OptimalSince the matrix is square, no new matrix is needed at all — swap matrix[i][j] with matrix[j][i] for every cell strictly above the main diagonal (j > i). Each such pair is swapped with its mirror below the diagonal exactly once, transposing the matrix in place with O(1) extra space.
O(n²)O(1)1class Solution {
2 public int[][] transposeMatrix(int[][] matrix) {
3 int n = matrix.length;
4 for (int i = 0; i < n; i++) {
5 for (int j = i + 1; j < n; j++) {
6 int temp = matrix[i][j];
7 matrix[i][j] = matrix[j][i];
8 matrix[j][i] = temp;
9 }
10 }
11 return matrix;
12 }
13}