Reshape the Matrix
Problem
Reshape a m×n matrix into r×c if m·n == r·c, preserving row-major order. Otherwise return the original matrix.
mat = [[1,2],[3,4]], r = 1, c = 4[[1,2,3,4]]def matrix_reshape(mat, r, c):
m, n = len(mat), len(mat[0])
if m * n != r * c: return mat
out = [[0]*c for _ in range(r)]
for k in range(m*n):
out[k//c][k%c] = mat[k//n][k%n]
return out
function matrixReshape(mat, r, c) {
const m = mat.length, n = mat[0].length;
if (m * n !== r * c) return mat;
const out = Array.from({ length: r }, () => new Array(c));
for (let k = 0; k < m * n; k++) out[(k/c)|0][k%c] = mat[(k/n)|0][k%n];
return out;
}
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length, n = mat[0].length;
if (m * n != r * c) return mat;
int[][] out = new int[r][c];
for (int k = 0; k < m * n; k++) out[k/c][k%c] = mat[k/n][k%n];
return out;
}
}
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>> out(r, vector<int>(c));
for (int k = 0; k < m * n; k++) out[k/c][k%c] = mat[k/n][k%n];
return out;
}
Explanation
Reshaping a matrix is really just renumbering the same cells. The trick is to imagine the whole grid flattened into one long line of m·n values read row by row, then poured back into the new shape the same way.
First we check feasibility: a reshape is only possible when m·n == r·c, i.e. the total number of cells matches. If not, we just return the original matrix unchanged.
If it fits, we loop over a single flat index k from 0 to m·n - 1. The clever part is the index math: in the source, cell k lives at row k/n and column k%n; in the target it lives at row k/c and column k%c. We copy mat[k/n][k%n] into out[k/c][k%c].
Example: mat = [[1,2],[3,4]], r = 1, c = 4. The flat order is 1, 2, 3, 4. Poured into a 1×4 grid that becomes [[1, 2, 3, 4]].
Each cell is touched exactly once, so the work is proportional to the number of elements.