Magicsheet logo

Reshape the Matrix

Easy
91.2%
Updated 6/1/2025

Reshape the Matrix

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

Matrix:

[[1, 2],
 [3, 4]]

Reshape to 1 × 4: mn = 4 = rc → valid.

  • k=0: original (0,0)=1 → new (0,0).
  • k=1: original (0,1)=2 → new (0,1).
  • k=2: original (1,0)=3 → new (0,2).
  • k=3: original (1,1)=4 → new (0,3).

Result: [[1, 2, 3, 4]].

Reshape 2×2 to 3×2: 4 ≠ 6 → return original [[1,2],[3,4]].

Common mistakes candidates make

  • Not checking whether m * n == r * c first, causing index out-of-bounds errors.
  • Using incorrect index formulas — the new column count c (not n) must be used to compute new row/col from k.
  • Creating an intermediate flat list unnecessarily — direct index mapping is cleaner.
  • Confusing row-major (C-order) with column-major (Fortran-order) traversal.

Interview preparation tip

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.

Similar Questions