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.
1class Solution {
2 public int[][] transpose(int[][] matrix) {
3 int rows = matrix.length;
4 int cols = matrix[0].length;
5 int[][] transposed = new int[cols][rows];
6 for (int i = 0; i < rows; ++i) {
7 for (int j = 0; j < cols; ++j) {
8 transposed[j][i] = matrix[i][j];
9 }
10 }
11 return transposed;
12 }
13}
A transposed matrix is created by initializing a new 2D array with transposed dimensions and mapping each element from the original matrix to its transposed position.
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)
1#include <vector>
using namespace std;
void transposeInPlace(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
}
Using C++'s swap
, the method rearranges elements in-place for square matrices by swapping pairs across the diagonal.