LeetCode 867: Transpose Matrix
Problem Description
Explanation
To transpose a matrix, we need to flip the matrix over its main diagonal, which means swapping the rows and columns. We can achieve this by iterating through the original matrix and constructing a new transposed matrix. The transposed matrix will have the number of rows equal to the number of columns of the original matrix and vice versa.
-
Algorithm:
- Initialize a new 2D array to store the transposed matrix with dimensions
n x m
. - Iterate through each element of the original matrix.
- Place the element at position
(i, j)
in the original matrix to position(j, i)
in the transposed matrix. - Return the transposed matrix.
- Initialize a new 2D array to store the transposed matrix with dimensions
-
Time Complexity: O(m * n) where
m
andn
are the dimensions of the original matrix. -
Space Complexity: O(m * n) for the transposed matrix.
Solutions
class Solution {
public int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] transposed = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
}
Related LeetCode Problems
Loading editor...