Reshape the Matrix - Problem
Imagine you have a data transformation challenge similar to what data scientists face daily! You're given a matrix (2D array) and need to reshape it into a different configuration while preserving all the original data in the same order.
Given an m × n matrix mat and two integers r and c, your task is to reshape the matrix into an r × c matrix. The reshaping should follow these rules:
- 🔄 Same row-traversing order: Fill the new matrix by reading the original matrix row by row, left to right
- ✅ Validate dimensions: Only reshape if
m × n = r × c(same total elements) - ❌ Invalid reshape: Return the original matrix unchanged if reshaping is impossible
Example: Transform [[1,2],[3,4]] with r=1, c=4 → [[1,2,3,4]]
Input & Output
example_1.py — Basic Reshape
$
Input:
mat = [[1,2],[3,4]], r = 1, c = 4
›
Output:
[[1,2,3,4]]
💡 Note:
We transform a 2×2 matrix into a 1×4 matrix. Reading the original matrix row by row gives us [1,2,3,4], which becomes a single row in the result.
example_2.py — 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 the target has 8 elements (2×4=8). Since 4≠8, the reshape is impossible, so we return the original matrix unchanged.
example_3.py — Vertical Reshape
$
Input:
mat = [[1,2,3,4]], r = 4, c = 1
›
Output:
[[1],[2],[3],[4]]
💡 Note:
We transform a 1×4 matrix (single row) into a 4×1 matrix (single column). Each element becomes its own row in the result.
Visualization
Tap to expand
Understanding the Visualization
1
Validate Reshape
Check if total elements match: original m×n must equal target r×c
2
Calculate Linear Index
For each element at position (i,j), find its sequential position: idx = i×n + j
3
Map to New Position
Place element at new coordinates: newRow = idx÷c, newCol = idx%c
4
Build Result
Continue until all elements are repositioned in the new matrix layout
Key Takeaway
🎯 Key Insight: Matrix reshaping is essentially a coordinate transformation problem - convert from one 2D indexing system to another while preserving element order through linear indexing.
Time & Space Complexity
Time Complexity
O(m*n)
Single pass through all elements in the matrix
✓ Linear Growth
Space Complexity
O(1)
Only the result matrix is needed, no extra auxiliary space
✓ Linear Space
Constraints
- m == mat.length
- n == mat[i].length
- 1 ≤ m, n ≤ 100
- 1 ≤ mat[i][j] ≤ 1000
- 1 ≤ r, c ≤ 300
- The total number of elements must be preserved
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code