Reshape the Matrix — LeetCode 566 Python Solution

EasyArrayMatrixSimulation
Problem
#566
Reading time
2 min

The problem

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.

Example

Input
mat = [[1,2],[3,4]], r = 1, c = 4
Output
[[1,2,3,4]]

Python solution

Python
class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        if m * n != r * c:
            return mat
        ans = [[0] * c for _ in range(r)]
        for i in range(m * n):
            ans[i // c][i % c] = mat[i // n][i % n]
        return ans

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of the original matrix, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 566. Reshape the Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 566. Reshape the Matrix?
LeetCode 566. Reshape the Matrix is rated Easy on LeetCode.
What is the time complexity of LeetCode 566. Reshape the Matrix?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of the original matrix, respectively.
What is the space complexity of LeetCode 566. Reshape the Matrix?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 566. Reshape the Matrix cover?
LeetCode 566. Reshape the Matrix is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview