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 with m rows and n columns contains exactly m * n cells. The 1D array can fill that matrix using every element exactly once only when its length equals that cell count. If the counts differ, some cells would be empty or some input values would have nowhere to go, so the correct result is an empty 2D array.
When the sizes match, fill the matrix row by row. Row i starts after the i previous rows, so its first value is at index i * n in original. Moving across column j advances j more positions, giving the direct mapping original[i * n + j]. This preserves the required order and avoids maintaining a separate input pointer.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(m * n) | The nested loops visit each of the m * n destination cells once, and each visit performs one indexed read and one assignment. The size check is constant work, so it does not change the bound. |
| Space | O(1) extra | The returned matrix contains m * n values and is required output, so it is excluded from the extra-space bound. Apart from that result, the algorithm keeps only loop indices and references; the bound remains O(1) for every input shape. |
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if (original.size() != static_cast<size_t>(m) * n) {
return {};
}
vector<vector<int>> ans(m, vector<int>(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ans[i][j] = original[i * n + j];
}
}
return ans;
}
};You can also walk through the input with one index p and derive the destination coordinates from p. The row is p / n and the column is p % n, so each input value is placed once without nested loops. This has the same O(m * n) time and O(1) extra space as the row-and-column version; it is simply a compact alternative when you prefer one linear traversal.
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
if (original.size() != static_cast<size_t>(m) * n) {
return {};
}
vector<vector<int>> ans(m, vector<int>(n));
for (int p = 0; p < static_cast<int>(original.size()); ++p) {
ans[p / n][p % n] = original[p];
}
return ans;
}
};