Reshape the Matrix
Easy · Matrix · Array · Matrix · Simulation
Problem
You are given an m x n matrix mat and two integers r and c. Read the values of mat in row-major order (left to right, top to bottom) and lay them out again, in that same order, into a new matrix with r rows and c columns.
Return the reshaped matrix if the reshape is possible, which is exactly when r * c == m * n. If the counts differ, return the original mat unchanged.
Examples
Input: mat = [[1,2,3],[4,5,6]], r = 3, c = 2 Output: [[1,2],[3,4],[5,6]]
The six values are read as 1..6 and refilled two per row.
Input: mat = [[1,2,3],[4,5,6]], r = 1, c = 6 Output: [[1,2,3,4,5,6]]
All six values fit in a single row of length 6.
Input: mat = [[9,8],[7,6]], r = 3, c = 2 Output: [[9,8],[7,6]]
A 3 x 2 matrix needs 6 cells but only 4 exist, so the input is returned as is.
Constraints
- m == mat.length, n == mat[i].length
- 1 <= m, n <= 100
- -1000 <= mat[i][j] <= 1000
- 1 <= r, c <= 300
Approaches
- Baseline: flatten, then cut — time O(m·n), space O(m·n)
Follow-up
The index map k → (k // cols, k % cols) is how a grid is stored in one block of memory, and reshaping is just reading the same block with a different width. The use cases build a grid from a flat list and reshape in column order instead.
Related problems
Start free on Cariara · Coding problems · System design studio