Reshape the Matrix - Problem

In MATLAB, there is a handy function called reshape which can reshape an m × n matrix into a new one with a different size r × c keeping its original data.

You are given an m × n matrix mat and two integers r and c representing the number of rows and columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Input & Output

Example 1 — Basic Reshape
$ Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
💡 Note: The original 2×2 matrix has 4 elements. We reshape it to 1×4 by reading elements row by row: 1,2,3,4 and placing them in a single row.
Example 2 — Invalid Reshape
$ Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
💡 Note: The original matrix has 4 elements (2×2=4) but target has 8 elements (2×4=8). Since reshape is impossible, return the original matrix.
Example 3 — Square to Rectangle
$ Input: mat = [[1,2,3],[4,5,6]], r = 3, c = 2
Output: [[1,2],[3,4],[5,6]]
💡 Note: Convert 2×3 matrix to 3×2 matrix. Reading row by row: 1,2,3,4,5,6 then fill new matrix: [[1,2],[3,4],[5,6]].

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 100
  • 1 ≤ r, c ≤ 300
  • -104 ≤ mat[i][j] ≤ 104

Visualization

Tap to expand
Reshape the Matrix INPUT Original Matrix (2x2) 1 2 3 4 Row-traversing order Parameters: mat = [[1,2],[3,4]] r = 1 c = 4 Total elements: 2x2 = 4 Target: 1x4 = 4 (OK) ALGORITHM STEPS 1 Validate Size Check m*n == r*c 2*2=4 == 1*4=4 [OK] 2 Flatten to 1D Read row by row 1 2 3 4 3 Index Mapping 1D idx to 2D position: row = idx / c col = idx % c 4 Fill New Matrix Place elements in new r x c matrix idx: 0-->(0,0) 1-->(0,1) idx: 2-->(0,2) 3-->(0,3) FINAL RESULT Reshaped Matrix (1x4) 1 2 3 4 [0,0] [0,1] [0,2] [0,3] Output: [[1, 2, 3, 4]] OK - Valid Reshape 2x2 matrix reshaped to 1x4 Same data, new dimensions Order preserved! Key Insight: Direct index mapping: For any 1D index i, the position in new matrix is (i/c, i%c). Reshape is valid only when m*n equals r*c - total elements must match! Time: O(m*n) | Space: O(1) extra (excluding output matrix) TutorialsPoint - Reshape the Matrix | Direct Mapping with Index Conversion
Asked in
Google 15 Amazon 12 Microsoft 8
186.3K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen