Reshape the Matrix (LeetCode 566): Solution and Explanation
Given an m x n matrix and a target shape r x c, rebuild the matrix with the same values in the same row-major order. When the target cannot hold exactly m * n values, return the original matrix.
Intuition
Read any matrix row by row and you get one long sequence of values. Reshaping does not change that sequence at all. It only changes where the sequence is cut into rows: every n values for the input, every c values for the output.
So give each value a single position k in that sequence. Position k lives at row k // n, column k % n of the input, and at row k // c, column k % c of the output.
The only way to fail is a size mismatch. If r * c is not m * n, the sequence would either run out early or leave values behind, so the problem says to return mat unchanged.
Approach: Single flat index
- Let
m = len(mat)andn = len(mat[0]). Ifm * n != r * c, returnmat. - Allocate
reswithrrows andccolumns. - For
kfrom0tom * n - 1, setres[k // c][k % c] = mat[k // n][k % n]. - Return
res.
Step-by-step example
mat = [[1,2],[3,4]], r = 1, c = 4
- m = 2, n = 2, so mat holds 4 values. r * c = 1 * 4 = 4, so the reshape is legal.
- Allocate a 1 x 4 result.
- k = 0: mat[0][0] = 1 goes to res[0][0]. k = 1: mat[0][1] = 2 goes to res[0][1].
- k = 2: mat[1][0] = 3 goes to res[0][2]. k = 3: mat[1][1] = 4 goes to res[0][3].
- The result is [[1,2,3,4]].
Code: Python, Java, C++
1class Solution:
2 def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
3 m, n = len(mat), len(mat[0])
4 if m * n != r * c:
5 return mat
6 res = [[0] * c for _ in range(r)]
7 for k in range(m * n):
8 res[k // c][k % c] = mat[k // n][k % n]
9 return res1class Solution {
2 public int[][] matrixReshape(int[][] mat, int r, int c) {
3 int m = mat.length, n = mat[0].length;
4 if (m * n != r * c) {
5 return mat;
6 }
7 int[][] res = new int[r][c];
8 for (int k = 0; k < m * n; k++) {
9 res[k / c][k % c] = mat[k / n][k % n];
10 }
11 return res;
12 }
13}1class Solution {
2public:
3 vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
4 int m = mat.size(), n = mat[0].size();
5 if (m * n != r * c) {
6 return mat;
7 }
8 vector<vector<int>> res(r, vector<int>(c));
9 for (int k = 0; k < m * n; k++) {
10 res[k / c][k % c] = mat[k / n][k % n];
11 }
12 return res;
13 }
14};Time and space complexity
O(m * n)
Each value is read once and written once.
O(m * n)
The output holds m * n values; besides it only the index k is used.
Other approaches
Flatten then cut (time O(m * n), space O(m * n))
Build a flat list of all values, then slice it into rows of length c. Easy to read, but it stores the values twice.
Two moving cursors (time O(m * n), space O(m * n))
Walk the input with (i, j) and the output with (row, col), advancing the output column and wrapping to the next row when it reaches c. Same work as the flat index, with more bookkeeping.
Common mistakes
- Dividing by the wrong width: the input uses
nand the output usesc. - Returning an empty matrix instead of
matwhen the sizes do not match. - Using integer division in a language where
/gives a float (JavaScript needsMath.floor). - Building rows with
[[0] * c] * rin Python, which shares one list across all rows.
Frequently asked questions
When is a reshape impossible?
Exactly when r * c is different from m * n. The target would need more or fewer values than the matrix has, so the original matrix is returned.
Why does the flat index formula work?
In row-major order, row i starts at position i * width. So position k is in row k // width at column k % width. Using the input width for reading and the output width for writing keeps the order identical.
What is the time and space complexity of Reshape the Matrix?
O(m * n) time to copy every value once, and O(m * n) space for the returned matrix.