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
Matrix Reshape: Preserve Row-Traversal Order1234Original 2×2Check: 2×2 = 1×4 ✓Row order: 1→2→3→41234Reshaped 1×4
Understanding the Visualization
1
Input Matrix
Original m×n matrix with elements in row order
2
Check Validity
Verify m×n = r×c for valid reshape
3
Reshape Output
New r×c matrix with same elements in row order
Key Takeaway
🎯 Key Insight: Matrix reshaping is only possible when the total number of elements remains constant
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