In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of 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.
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]]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n <= 100-1000 <= mat[i][j] <= 10001 <= r, c <= 300This approach involves two main steps: flattening the original matrix into a one-dimensional array and then reconstructing it into the desired dimensions. The flattening process collects all elements by iterating row-wise over the original matrix. Then, if the total number of elements matches the product of new dimensions r and c, the method distributes these elements row-wise into the new matrix. If the element count does not match, the original matrix is returned.
The C code first checks if the reshape can be performed by comparing the number of elements in the original and desired matrices. If possible, it allocates memory for the new matrix and reshapes by using modulus and division to determine the new indices based on flattened array index i.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n) where m and n are the dimensions of the original matrix.
Space Complexity: O(r * c) for the reshaped matrix.
Index Mirroring leverages mathematical transformation to directly address elements from the original matrix into the new shape without explicitly flattening. It avoids extra space for a flat array and directly computes 2D indices in the new layout.
In this solution, we directly calculate the new position (index / c, index % c) for elements from the original position (i, j) in mat, avoiding the need for an intermediate one-dimensional array.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n).
Space Complexity: O(r * c) for storing reshaped matrix.
| Approach | Complexity |
|---|---|
| Flatten and Reconstruct | Time Complexity: O(m * n) where m and n are the dimensions of the original matrix. |
| Index Mirroring | Time Complexity: O(m * n). |
Transpose Matrix - Leetcode 867 - Python • NeetCodeIO • 14,120 views views
Watch 9 more video solutions →Practice Reshape the Matrix with our built-in code editor and test cases.
Practice on FleetCode