Transpose of a Matrix

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given a square matrix matrix, 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:

Input:matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:[[1,4,7],[2,5,8],[3,6,9]]
Explanation:Every cell (i, j) moves to (j, i) — rows become columns.

Test Case 2:

Input:matrix = [[1,2],[3,4]]
Output:[[1,3],[2,4]]
Explanation:A 2×2 matrix's off-diagonal pair simply swaps places.

Test Case 3:

Input:matrix = [[5]]
Output:[[5]]
Explanation:A single cell is its own transpose.

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.

🧪Try your own test case
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}
14
1
2
3
4
5
6
7
8
9
Variables
n3
INITIALIZE

Transpose in place: swap matrix[i][j] with matrix[j][i] for every pair above the main diagonal — no new matrix needed.

Step 1 / 5

Approach & Solutions

Brute Force — Extra Matrix

Brute

Allocate 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.

TimeO(n²)
SpaceO(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

Optimal

Since 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.

TimeO(n²)
SpaceO(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}

Related Problems