Reshape the Matrix
Difficulty: Easy · Pattern: Matrix · LeetCode #566
Reshape mat into an r × c matrix, filling it in row-major order with the original elements. If that's impossible (the element counts differ), return the original matrix.
Examples
text
mat = [[1,2],[3,4]], r = 1, c = 4 → [[1,2,3,4]]
mat = [[1,2],[3,4]], r = 2, c = 4 → [[1,2],[3,4]] (impossible)Hints
- Number every element by its row-major index k. Its position in an R×C matrix is
(k // C, k % C).
Approach
If R·C != r·c, return mat. Otherwise, for each k: res[k // c][k % c] = mat[k // C][k % C].
This flat-index ↔ 2-D conversion is how languages store matrices in memory. It's also how binary search runs on a sorted matrix (Search a 2D Matrix) and how NumPy's reshape works without copying.
Complexity
Time: O(R·C). Space: O(R·C) for the output.
Python solution
def matrixReshape(mat, r, c):
R, C = len(mat), len(mat[0])
if R * C != r * c:
return mat
flat = [x for row in mat for x in row]
return [flat[i * c:(i + 1) * c] for i in range(r)]JavaScript solution
function matrixReshape(mat, r, c) {
const R = mat.length, C = mat[0].length;
if (R * C !== r * c) return mat;
const res = Array.from({ length: r }, () => new Array(c));
for (let k = 0; k < R * C; k++) res[Math.floor(k / c)][k % c] = mat[Math.floor(k / C)][k % C];
return res;
}