Reshape the Matrix — Solution in Python, Java & C++
Reshape the Matrix solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and matrix.
Reshape the Matrix is an easy coding problem on arrays, matrix and simulation, asked in Amazon, Microsoft, Adobe and MathWorks interviews.
- Difficulty: Easy
- Topics: Arrays, Matrix, Simulation
- Asked at: Amazon, Microsoft, Adobe, MathWorks
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given an m × n matrix mat and two integers r and c giving the number of rows and columns of a wanted reshaped matrix.
The reshaped matrix must contain all the original elements in the same row-traversing order. If the reshape is not legal — the element counts differ — return the original matrix.
Example 1
Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Example 2
Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
Explanation: 4 elements cannot fill 8 slots, so the original is returned.
Example 3
Input: mat = [[1,2,3,4]], r = 2, c = 2
Output: [[1,2],[3,4]]
Constraints
1 <= mat.length, mat[i].length <= 8-1000 <= mat[i][j] <= 10001 <= r, c <= 40
Hints for Reshape the Matrix
Hint 1
Check
m × n == r × cfirst; anything else returns the input unchanged.Hint 2
Flatten in row order, then slice into rows of length
c.Hint 3
Without flattening: element
kof the reading order sits at(k / n, k % n)in the source and(k / c, k % c)in the target.
How to solve Reshape the Matrix
If the element counts match, read the matrix in row order and cut it into rows of length c.
Approach
- Return
matunchanged ifm · n != r · c. - Flatten row by row.
- Slice the flat list into
rrows ofcelements.
Why it works
Reshaping preserves the row-major reading order, so the flat sequence is the invariant and only the row breaks move.
Complexity
- Time —
O(m · n) - Space —
O(m · n)
Pitfalls
- Index arithmetic (
flat[k]at(k // n, k % n)→(k // c, k % c)) avoids the intermediate list.
Reference solution
Python
def matrixReshape(mat, r: int, c: int):
rows, cols = len(mat), len(mat[0])
if rows * cols != r * c:
return mat
flat = [v for row in mat for v in row]
return [flat[i * c:(i + 1) * c] for i in range(r)]Java
public static int[][] matrixReshape(int[][] mat, int r, int c) {
int rows = mat.length, cols = mat[0].length;
if (rows * cols != r * c) return mat;
int[][] out = new int[r][c];
for (int k = 0; k < r * c; k++) {
out[k / c][k % c] = mat[k / cols][k % cols];
}
return out;
}C++
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int rows = (int) mat.size(), cols = (int) mat[0].size();
if (rows * cols != r * c) return mat;
vector<vector<int>> out(r, vector<int>(c, 0));
for (int k = 0; k < r * c; k++) {
out[k / c][k % c] = mat[k / cols][k % cols];
}
return out;
}JavaScript
var matrixReshape = function(mat, r, c) {
const rows = mat.length, cols = mat[0].length;
if (rows * cols !== r * c) return mat;
const flat = [];
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) flat.push(mat[i][j]);
}
const out = [];
for (let i = 0; i < r; i++) out.push(flat.slice(i * c, i * c + c));
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Matrix and Grid Traversal