Opening the reading…
Opening the reading…
MATRIX › MATRIX TRANSFORMATION AND MODIFICATION
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A matrix entry is identified by two coordinates: its row and its column. Transposing does not change the value; it changes which coordinate is treated as the row and which is treated as the column. Therefore, an entry at original position i, j must appear at position j, i in the result.
If the original matrix has m rows and n columns, the result has n rows and m columns. Each original row becomes a result column, while each original column becomes a result row. Allocate that shape first, then visit every original position exactly once and write its value into the swapped position.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(m x n) | The nested loops process every one of the m x n input entries once, and each iteration performs one constant-time assignment. No entry is revisited or compared with another. |
| Space | O(m x n) extra | The result stores m x n integers and is required output, so it is excluded from the extra-space bound. Apart from that output, the algorithm keeps only the dimensions and loop variables, which use O(1) working memory. |
#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>> result(n, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
};The allocation and assignment lines work together. result has n rows because each original column becomes a result row, and each result row has m entries because it receives one value from every original row. The assignment uses result[j][i], not result[i][j], which is the exact coordinate swap that defines transposition.