The Reshape the Matrix interview question asks you to reshape an m × n matrix into a new r × c matrix, filling it row by row with the same elements in the same row-traversal order as the original. If the reshape is not possible (i.e., m * n ≠ r * c), return the original matrix unchanged.
MathWorks, Meta, and Amazon ask this problem because matrix reshaping is a foundational operation in scientific computing, machine learning (tensor reshaping in NumPy/PyTorch), and image processing. It tests understanding of row-major order traversal and index arithmetic — mapping a 2D index to a 1D position and back. These skills are directly relevant to GPU programming and data pipeline design.
The pattern is matrix flattening and refilling with index arithmetic. First, verify that m * n == r * c. Then, traverse the original matrix in row-major order (left to right, top to bottom) and fill the new matrix the same way. Use the formula: for the k-th element (0-indexed), original indices are (k // n, k % n) and new indices are (k // c, k % c).
This avoids explicitly creating a 1D flat array — you can directly map indices.
Matrix:
[[1, 2],
[3, 4]]
Reshape to 1 × 4: mn = 4 = rc → valid.
Result: [[1, 2, 3, 4]].
Reshape 2×2 to 3×2: 4 ≠ 6 → return original [[1,2],[3,4]].
m * n == r * c first, causing index out-of-bounds errors.c (not n) must be used to compute new row/col from k.For the Reshape the Matrix coding problem, the array and matrix simulation interview pattern is straightforward once you understand the index mapping: k = row * cols + col for flattening, and (k // new_cols, k % new_cols) for refilling. Practice writing this mapping clearly. Interviewers at MathWorks and Meta appreciate when you connect this to NumPy's reshape() function in real-world usage — it shows applied knowledge beyond the abstract problem.