Transpose Matrix

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example

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]]
Constraints:

Contents

Solution 1 - Convert rows to columns

In this approach, we will simply convert rows to columns.

Implementation steps:
  • Create a variable result 2D array with rows length as columns length input array, and columns length as rows length input array.
  • Then, loop through for each row i and column j of input array matrix, add the value to row j and column i of result array.
Java
import java.util.Arrays;
import java.util.stream.Stream;

public class TransposeMatrix {

    static int[][] transposeMatrix(int[][] matrix) {
        if(matrix == null) {
            return null;
        }
        int[][] result = new int[matrix[0].length][matrix.length];
        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[i].length; j++) {
                result[j][i] = matrix[i][j];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] result = transposeMatrix(new int[][] {{1,2}});
        Stream.of(result).forEach(row->System.out.println(Arrays.toString(row)));
        result = transposeMatrix(new int[][] {{1,2}, {3,4}, {5,6}});
        Stream.of(result).forEach(row->System.out.println(Arrays.toString(row)));
        result = transposeMatrix(new int[][] {{}});
        Stream.of(result).forEach(row->System.out.println(Arrays.toString(row)));
    }
}
Complexity Analysis:

Time complexity: Above code runs in O(m * n) time where m is rows length, and n is columns length of input array matrix.
Space complexity: O(m * n) for the result array.

Above implementations source code can be found at GitHub link for Java code