Sponsored
Sponsored
This approach involves two main steps: flattening the original matrix into a one-dimensional array and then reconstructing it into the desired dimensions. The flattening process collects all elements by iterating row-wise over the original matrix. Then, if the total number of elements matches the product of new dimensions r
and c
, the method distributes these elements row-wise into the new matrix. If the element count does not match, the original matrix is returned.
Time Complexity: O(m * n) where m and n are the dimensions of the original matrix.
Space Complexity: O(r * c) for the reshaped matrix.
1var matrixReshape = function(mat, r, c) {
2 const m = mat.length, n = mat[0].length;
3 if (m * n !== r * c) return mat;
4
5 const flat = [].concat(...mat);
6 const result = [];
7 for (let i = 0; i < r; i++) {
8 result.push(flat.slice(i * c, i * c + c));
9 }
10 return result;
11};
12
The JavaScript solution begins by checking feasibility, then flattens the matrix using the spread syntax [].concat(...mat)
before slicing it back into row-sized chunks for the desired reshaping.
Index Mirroring leverages mathematical transformation to directly address elements from the original matrix into the new shape without explicitly flattening. It avoids extra space for a flat array and directly computes 2D indices in the new layout.
Time Complexity: O(m * n).
Space Complexity: O(r * c) for storing reshaped matrix.
1#include <vector>
using namespace std;
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<vector<int>> newMat(r, vector<int>(c));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int index = i * n + j;
newMat[index / c][index % c] = mat[i][j];
}
}
return newMat;
}
This C++ code maintains element continuity via index coordination. Element addresses transition between matrices of differing dimensions by recalculating new indices without pre-flattening.