Easy Array Problems Java

Transpose of a Matrix in Java

Print the transpose of a matrix, where rows become columns.

  • TimeO(rows * cols)
  • SpaceO(rows * cols) with a new matrix, O(1) in place
  • Hints3
  • Read2 min
Quick answer

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.

2D arraysNested loopsIn-place swap
1

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.

Input

A matrix with the given number of rows and columns.

Output

The transposed matrix.

Examples

Example 1
Input[[1, 2, 3], [4, 5, 6]]
Output[[1, 4], [2, 5], [3, 6]]

The row 1 2 3 is now the first column.

Example 2
Input[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output[[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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Swap the two index numbers: the value at [i][j] goes to [j][i].
2 Hint 2
For any size, make a new array with cols rows and rows columns.
3 Hint 3
To work in place, start the inner loop at j = i + 1 so each pair is swapped only once.
4

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

  1. Read rows and cols.
  2. Create t with cols rows and rows columns.
  3. Visit every cell and copy it with the two index numbers swapped.

Square, in place

  1. Visit only the cells above the main diagonal (j > i).
  2. Swap m[i][j] with m[j][i].

Need a refresher? Read arrays in Java. The swap uses a temporary variable, though you can also swap without one.

5

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
6

Solution

Reveal the full Java solution
Solution.java
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.

TimeO(rows * cols)
SpaceO(rows * cols) with a new matrix, O(1) in place
7

Review 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

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us