Transpose Matrix
Given a 2D integer array matrixmatrix
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,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]]
Output: [[1,4],[2,5],[3,6]]
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10001 <= m * n <= 105-109 <= matrix[i][j] <= 109
Contents
Solution 1 - Convert rows to columns
In this approach, we will simply convert rowscolumns
Implementation steps:
-
Create a variable
2D array with rows length as columns length input array, and columns length as rows length input array.result -
Then, loop through for each row
and columni of input arrayj , add the value to rowmatrix and columnj ofi array.result
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 mnmatrix
Space complexity: O(m * n) for the result array.
Above implementations source code can be found at