Problem
Given an mΓn matrix and a target shape of r rows and c columns, return a new matrix containing all the same elements in row-major (left-to-right, top-to-bottom) order. If the total element count doesn't match (mΓn β rΓc), return the original matrix unchanged.
- Input:
mat = [[1,2],[3,4]],r = 1,c = 4 - Output:
[[1,2,3,4]] - Explanation: The four elements are read left-to-right, top-to-bottom from the 2Γ2 source and placed into a single 1Γ4 row.
Counter-example: mat = [[1,2],[3,4]], r = 2, c = 4 has no valid reshape because 2Γ2 = 4 β 2Γ4 = 8; return the original matrix.
Intuition
Every element occupies a unique position k in a flat, row-major sequence regardless of the matrix's shape. Knowing k, the source coordinates are (k // n, k % n) and the destination coordinates are (k // c, k % c). A single loop over all mΓn indices remaps each element without ever building an intermediate 1D array.
Solution β Index Arithmetic
Check feasibility first, then use integer division and modulo to map each flat index to its source and destination coordinates.
- Compute
m = len(mat)andn = len(mat[0]). - If
m * n != r * c, returnmatimmediately β reshape would change the element count. - Allocate the result grid of size
r Γ c. - For each flat index
kfrom0tom*n β 1, read frommat[k // n][k % n]and write toresult[k // c][k % c]. - Return the result.
1def matrixReshape(mat: list[list[int]], r: int, c: int) -> list[list[int]]:
2 m, n = len(mat), len(mat[0])
3 if m * n != r * c: # reshape would change element count, which is illegal
4 return mat
5
6 result = [[0] * c for _ in range(r)]
7 for k in range(m * n):
8 result[k // c][k % c] = mat[k // n][k % n]
9 return resultTime: O(mΓn) β each element is visited exactly once.
Space: O(rΓc) β the output matrix is the only allocation beyond input.
Complexity Summary
| Approach | Time | Space | When to use |
|---|---|---|---|
| Index Arithmetic | O(mΓn) | O(rΓc) | Any time a 2D grid needs to be reinterpreted as a different shape without materializing a flat intermediate |
Common Mistakes
- Skipping the feasibility check β attempting the reshape when
m*n != r*ccauses an index out-of-bounds error when writing intoresult; the check must come first. - Mixing up
nandcin the source formula β the source read usesk // nandk % n(divided by the original column count), while the destination write usesk // candk % c(divided by the target column count); usingcfor both silently reads from wrong source cells. - Returning
Noneor[]on failure instead ofmatβ the problem contract requires returning the original matrix when reshape is impossible, not an empty or null result. - Building an intermediate flat list β flattening to a 1D array first and then rebuilding the result doubles the memory allocation unnecessarily; the index formula eliminates that intermediate step.
Related Problems
Search a 2D Matrixβ also exploits row-major ordering to treat a 2D matrix as a virtual flat sorted array using the same index arithmeticSpiral Matrixβ traverses a 2D matrix in non-row-major order, requiring careful directional index trackingRotate Imageβ transforms a square matrix in-place by remapping (row, col) to (col, mβ1βrow), a harder in-place variant of 2D index manipulationSet Matrix Zeroesβ iterates a 2D matrix and modifies it based on discovered indices, requiring careful ordering to avoid overwriting sentinel valuesMatrix Diagonal Sumβ uses index arithmetic to selectively access specific positions in a 2D grid without a full traversal