Transpose Matrix

Turn each row of a matrix into a column, so a grid with m rows and n columns becomes one with n rows and m columns.

You are given a 2D integer array matrix with at least one row and one column. Return its transpose: a new matrix in which each row of matrix becomes a column. The first row becomes the first column, the second row becomes the second column, and so on.

Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Example 2
Input: matrix = [[1, 2, 3], [4, 5, 6]]
Output: [[1, 4], [2, 5], [3, 6]]
Explanation: a matrix with 2 rows and 3 columns becomes one with 3 rows and 2 columns.
Solution

The Idea

You have probably seen a table turned on its side. A sheet with months along the top and names down the side gets flipped, so the months run down the side and the names along the top. Spreadsheet programs call this transposing, and this problem asks for the same thing on a grid of numbers.

In Java the grid is a 2D array, also called a matrix. matrix[i] is row i, and matrix[i][j] is the value in row i, column j, both counted from 0. Look at Example 2. Its two rows are 1, 2, 3 and 4, 5, 6. In the output, 1, 2, 3 reads down the first column and 4, 5, 6 down the second. The grid also changed shape: 2 rows of 3 values became 3 rows of 2.

Seeing whole rows move is one thing, but code copies one value at a time. So for a single value, where exactly does it go? Look at the picture below.

The matrix [[1, 2, 3], [4, 5, 6]] with 2 rows and 3 columns, and the result [[1, 4], [2, 5], [3, 6]] with 3 rows and 2 columns. Row 1, which is 4, 5, 6, becomes column 1. The value 6 moves from row 1, column 2 to row 2, column 1.

On the left, row 1 of matrix is 4, 5, 6. On the right, the same three numbers fill column 1 of the result. Now follow the value 6. It sits in row 1, column 2, and it lands in row 2, column 1. The row number and the column number have traded places.

That holds for every value: the value in row i, column j goes to row j, column i. A value whose row and column numbers are equal stays where it is, like 1 in row 0, column 0 and 5 in row 1, column 1. Those cells form a line running down from the top-left corner, called the main diagonal. That is why a transpose is often described as flipping the matrix over its main diagonal.

Solution Approach

Turning that rule into code means settling two things: how big the result is, and in what order to fill it. A third, optional question is whether a square matrix can be transposed without a new array.

The size of the result

How many rows and columns does the result need? Call the number of rows in matrix m and the number of columns n. Each row of matrix becomes a column, so the result has n rows of m values: new int[n][m].

Giving the result the input's shape, new int[m][n], only works for square matrices. For Example 2 that array has two rows, so the third value, 3, has nowhere to go. Writing it to result[2][0] throws ArrayIndexOutOfBoundsException.

Filling the result

In what order should the values be copied? Any order works, because each value has exactly one place to go and no two values share a place. The simplest is to read matrix row by row and write each value to its swapped position. Every value has to be copied once anyway, so no method can do less work than that.

Transposing a square matrix in place

Could a square matrix, with as many rows as columns, skip the new array? The result has the same shape, so the values can be swapped inside matrix itself. The swaps must only visit the cells above the main diagonal, where j > i. Swapping for every i and j swaps each pair twice, once from each side, and puts it back.

Trying both ways on [[1, 2, 3], [4, 5, 6], [7, 8, 9]] shows the difference. Swapping for every pair leaves the matrix exactly as it was. Swapping only where j > i gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. An in-place swap changes the caller's array, though, so the solution below builds a new one.

Java Solution

The method transpose works in these steps:

  1. First, read the size of the input: m = matrix.length is the number of rows, and n = matrix[0].length is the number of columns.
  2. Create the result with the shape flipped, result = new int[n][m]: n rows of m values.
  3. Visit every value of matrix with two loops, one inside the other. The outer loop moves i over the rows, and the inner loop moves j over the columns of row i.
  4. Copy each value to its swapped position with result[j][i] = matrix[i][j].
  5. When both loops are done, return result.

The main method transposes both examples, a matrix with one row, a matrix with one column and a matrix with a single value. Last, it prints the input of Example 1 again.

Java
import java.util.Arrays;

public class TransposeMatrix {

    public static int[][] transpose(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] result = new int[n][m];        // the shape flips: m x n becomes n x m
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                result[j][i] = matrix[i][j];   // row i, column j goes to row j, column i
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] square = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(Arrays.deepToString(transpose(square)));
        System.out.println(Arrays.deepToString(transpose(new int[][] {{1, 2, 3}, {4, 5, 6}})));
        System.out.println(Arrays.deepToString(transpose(new int[][] {{1, 2, 3}})));
        System.out.println(Arrays.deepToString(transpose(new int[][] {{7}, {8}, {9}})));
        System.out.println(Arrays.deepToString(transpose(new int[][] {{5}})));
        System.out.println(Arrays.deepToString(square));   // the input is not changed
    }
}

Running it prints:

Output
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[[1, 4], [2, 5], [3, 6]]
[[1], [2], [3]]
[[7, 8, 9]]
[[5]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Look at the second line, [[1, 4], [2, 5], [3, 6]]: three rows of two values, made from the two rows of three in Example 2. The first line, from Example 1, keeps its 3 × 3 shape, and 1, 5 and 9 stay on the main diagonal.

The single row [[1, 2, 3]] comes out as the column [[1], [2], [3]], and the column [[7], [8], [9]] comes out as the row [[7, 8, 9]]. A single value, [[5]], is its own transpose, since it sits on the main diagonal.

The last line is [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the input of Example 1 just as it was. Every write went to result, never back into matrix.

The original implementation, TransposeMatrix.java, is on GitHub.

Complexity

The work is one copy of every value into a new array.

  • Time: O(m × n), because the two loops visit each of the m × n values once, m rows of n columns, with one read and one write each.
  • Space: O(m × n) for the result. result holds a copy of every value. Besides it, the method keeps only m, n, i and j.

Transposing a square matrix and then reversing each row turns it 90 degrees clockwise, the rotation asked for in Rotate Image.