Sponsored
Sponsored
To transpose the given matrix, we create a new matrix with dimensions transposed: the number of rows of the new matrix is equal to the number of columns in the original matrix, and vice versa. We fill in the new matrix by iterating through each element of the original matrix and placing it at the transposed position in the new matrix.
Time Complexity: O(m * n) where m and n are the number of rows and columns respectively.
Space Complexity: O(m * n) since a new matrix is created.
1public class Solution {
2 public int[][] Transpose(int[][] matrix) {
3 int rows = matrix.Length;
4 int cols = matrix[0].Length;
5 int[][] transposed = new int[cols][];
6 for (int j = 0; j < cols; ++j) {
7 transposed[j] = new int[rows];
8 for (int i = 0; i < rows; ++i) {
9 transposed[j][i] = matrix[i][j];
10 }
11 }
12 return transposed;
13 }
14}
C# implementation uses jagged arrays to transpose the matrix similar to the structure of the input matrix.
This approach specifically applies to square matrices where m = n. For such matrices, we can swap elements using an in-place technique, avoiding additional space usage. For each element above the main diagonal, swap it with its corresponding element below the diagonal.
Time Complexity: O(n^2)
Space Complexity: O(1)
1public class Solution {
public void TransposeInPlace(int[][] matrix) {
int n = matrix.Length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
}
C# solution that uses a temporary variable to swap elements across the main diagonal within the same matrix, strictly for square matrices.