Leetcode 867. Transpose Matrix
The problem “Transpose Matrix” can be found as problem number 867 on LeetCode. The task is as follows:
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.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
To transpose a matrix, we need to swap the rows and columns of the input matrix. This means that the element at position [i][j]
in the original matrix will be at position [j][i]
in the transposed matrix.
transpose[j][i] = matrix[i][j]
.The time complexity for this operation is (O(m \times n)), where m
is the number of rows and n
is the number of columns in the input matrix. This is because each element must be accessed once to be placed in the transposed matrix.
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> transposed(n, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
};
m
is the number of rows in the input matrix.n
is the number of columns in the input matrix.transposed
with dimensions n
x m
.i
.j
.matrix[i][j]
to transposed[j][i]
.This solution efficiently transposes the input matrix with a clear O(m * n) time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?