1. Flatten to 1D Array then Populate Reshaped Matrix
Intuition
Flatten the m x n matrix into a 1D array of size m*n, then fill the target r x c matrix sequentially.
Algorithm
- 1. Let m = mat.length, n = mat[0].length. If m * n != r * c, return mat.
- 2. Flatten: Push all m*n elements into a 1D list flat.
- 3. Create new matrix reshaped of dimensions r x c.
- 4. Fill reshaped: For k from 0 to m*n-1, reshaped[floor(k / c)][k % c] = flat[k].
- 5. Return reshaped.
Flatten to 1D Buffer then Populate Reshaped Matrix
2 of 2 questions left todayPhase 1 — Flattening First Row: Traverse mat[0] = [1, 2]
Phase 1 — Flattening First Row: Traverse mat[0] = [1, 2]. Extract elements into a temporary flat array: buffer = [1, 2].
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) { int m = mat.size(), n = mat[0].size(); if (m * n != r * c) return mat; vector<int> flat; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) flat.push_back(mat[i][j]); } vector<vector<int>> res(r, vector<int>(c)); for (int k = 0; k < m * n; ++k) { res[k / c][k % c] = flat[k]; } return res; }}; int main() { Solution sol; vector<vector<int>> mat = {{1, 2}, {3, 4}}; int r = 1, c = 4; vector<vector<int>> res = sol.matrixReshape(mat, r, c); cout << "Reshaped Matrix:" << endl; for (const auto& row : res) { cout << "["; for (size_t i = 0; i < row.size(); ++i) { cout << row[i] << (i + 1 < row.size() ? ", " : ""); } cout << "]" << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(M * N)— Iterates through all M x N elements twice in O(M * N) time. - Space complexity:
O(M * N)— Allocates an auxiliary 1D array of size M x N, consuming O(M * N) memory.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.