Transpose of a Matrix in Java
Print the transpose of a matrix, where rows become columns.
- Time
O(rows * cols) - Space
O(rows * cols) with a new matrix, O(1) in place - Hints3
- Read2 min
The transpose of a matrix turns its rows into columns: the value at row i, column j moves to row j, column i. In Java, make a new matrix of size cols x rows and set t[j][i] = m[i][j]. A square matrix can also be transposed in place by swapping the values across the main diagonal.
Problem statement
Find the transpose of a matrix in Java. The first row of the matrix becomes the first column of the answer, the second row becomes the second column, and so on.
A 2 x 3 matrix becomes a 3 x 2 matrix.
A matrix with the given number of rows and columns.
The transposed matrix.
Examples
[[1, 2, 3], [4, 5, 6]][[1, 4], [2, 5], [3, 6]]The row 1 2 3 is now the first column.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]][[1, 4, 7], [2, 5, 8], [3, 6, 9]]A square matrix keeps its size. The diagonal 1 5 9 does not move.
Constraints
- 1 <= rows, columns <= 1000
- The in-place version needs rows = columns
Think before you code
Reveal the questions to ask yourself first
- Where does the value at row 0, column 2 go?
- What is the size of the answer when the matrix is not square?
- In a square matrix, which values stay in the same place?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
The transpose of a matrix logic in Java is one line: t[j][i] = m[i][j].
Any size
- Read
rowsandcols. - Create
twithcolsrows androwscolumns. - Visit every cell and copy it with the two index numbers swapped.
Square, in place
- Visit only the cells above the main diagonal (
j > i). - Swap
m[i][j]withm[j][i].
Need a refresher? Read arrays in Java. The swap uses a temporary variable, though you can also swap without one.
Dry run
Walk through the example step by step
In-place transpose of [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:
i | j | swap | matrix after the swap
--+---+-----------+----------------------
0 | 1 | 2 and 4 | 1 4 3 / 2 5 6 / 7 8 9
0 | 2 | 3 and 7 | 1 4 7 / 2 5 6 / 3 8 9
1 | 2 | 6 and 8 | 1 4 7 / 2 5 8 / 3 6 9
Solution
Reveal the full Java solution
import java.util.Arrays;
public class MatrixTranspose {
// Works for any rows x cols matrix.
public static int[][] transpose(int[][] m) {
int rows = m.length;
int cols = m[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
// Square matrix only: no second matrix needed.
public static void transposeInPlace(int[][] m) {
for (int i = 0; i < m.length; i++) {
if (m[i].length != m.length) {
throw new IllegalArgumentException("Matrix must be square");
}
}
for (int i = 0; i < m.length; i++) {
for (int j = i + 1; j < m.length; j++) {
int temp = m[i][j];
m[i][j] = m[j][i];
m[j][i] = temp;
}
}
}
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(transpose(a)));
// [[1, 4], [2, 5], [3, 6]]
int[][] b = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
transposeInPlace(b);
System.out.println(Arrays.deepToString(b));
// [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
}
}The transpose of a matrix in Java program above has both methods. transpose works for
every size and leaves the original alone. transposeInPlace changes the matrix itself
and saves memory.
Transpose of a matrix in Java with user input
If you only want to print, you do not need a second array. Loop over the columns first, then the rows.
import java.util.Scanner;
public class TransposeInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter rows and columns:");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] m = new int[rows][cols];
System.out.println("Enter the values:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = sc.nextInt();
}
}
System.out.println("Transpose:");
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
}
}
For rows 2, columns 3 and the values 1 2 3 4 5 6, the last part of the output is:
Transpose:
1 4
2 5
3 6
Transpose of a matrix in Java in place
The in-place method works only for a square matrix, because a Java array cannot change
its size. The key is j = i + 1. If j starts at 0, each pair is swapped twice and the
matrix goes back to how it started.
Once you can find the transpose of a matrix in Java, try matrix multiplication and reversing an array in place. Transposing and then reversing each row turns a square matrix by 90 degrees clockwise. For guided practice, see the Java full stack course.
O(rows * cols)O(rows * cols) with a new matrix, O(1) in placeReview before the interview
Common mistakes
- Creating the answer as new int[rows][cols]. It must be new int[cols][rows].
- Starting j at 0 in the in-place version, which swaps every pair twice.
- Trying the in-place swap on a matrix that is not square.
Edge cases to test
- A single row becomes a single column.
- A 1 x 1 matrix stays the same.
- Rectangular matrices must use the new-matrix method.
Interview follow-ups
- How would you check if a matrix is symmetric?
- How do you rotate a square matrix by 90 degrees?
- How would you transpose a matrix too big to fit in memory?
Keep practising
Reverse an Array In Place
Hints · Dry run · SolutionSolve Similar problemRotate an Array to the Left by One Position
Hints · Dry run · SolutionSolve Similar problemSwap Two Numbers Without Using a Third Variable
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
