KatInterview

566. Reshape the Matrix

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to transform a given m x n matrix into a new r x c matrix. The key constraint is that the elements must be rearranged in the same "row-traversing order." This means if you were to read the elements of the original matrix row by row, from left to right, you would get a sequence. The new matrix must be filled with this same sequence, also row by row, left to right. A crucial condition for this transformation to be possible is that the total number of elements must remain the same. If the number of elements m * n in the original matrix is not equal to r * c in the target matrix, the reshape is impossible, and we should return the original matrix.

Solution

Reshape the Matrix in Python

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        
        # Check if the reshape operation is possible and legal.
        # The total number of elements must be the same.
        if m * n != r * c:
            return mat
        
        # Create the new reshaped matrix.
        reshaped = [[0] * c for _ in range(r)]
        
        # Iterate through all elements of the matrix using a single counter.
        # This conceptually flattens the matrix and then rebuilds it.
        for i in range(m * n):
            # Map the 1D index 'i' to 2D indices for both matrices.
            # Original matrix: mat[i // n][i % n]
            # New matrix: reshaped[i // c][i % c]
            # In Python, // is integer division.
            reshaped[i // c][i % c] = mat[i // n][i % n]
            
        return reshaped

Reshape the Matrix in Java

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int m = mat.length;
        int n = mat[0].length;

        // Check if the reshape operation is possible and legal.
        // The total number of elements must be the same.
        if (m * n != r * c) {
            return mat;
        }

        // Create the new reshaped matrix.
        int[][] reshaped = new int[r][c];

        // Iterate through all elements of the matrix using a single counter.
        // This conceptually flattens the matrix and then rebuilds it.
        for (int i = 0; i < m * n; i++) {
            // Map the 1D index 'i' to 2D indices for both matrices.
            // Original matrix: mat[i / n][i % n]
            // New matrix: reshaped[i / c][i % c]
            reshaped[i / c][i % c] = mat[i / n][i % n];
        }

        return reshaped;
    }
}

Reshape the Matrix in C++

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int m = mat.size();
        int n = mat[0].size();
        
        // Check if the reshape operation is possible and legal.
        // The total number of elements must be the same.
        if (m * n != r * c) {
            return mat;
        }
        
        // Create the new reshaped matrix.
        vector<vector<int>> reshaped(r, vector<int>(c));
        
        // Iterate through all elements of the matrix using a single counter.
        // This conceptually flattens the matrix and then rebuilds it.
        for (int i = 0; i < m * n; ++i) {
            // Map the 1D index 'i' to 2D indices for both matrices.
            // Original matrix: mat[i / n][i % n]
            // New matrix: reshaped[i / c][i % c]
            reshaped[i / c][i % c] = mat[i / n][i % n];
        }
        
        return reshaped;
    }
};

Reshape the Matrix in TypeScript

function matrixReshape(mat: number[][], r: number, c: number): number[][] {
    const m = mat.length;
    const n = mat[0].length;

    // Check if the reshape operation is possible and legal.
    // The total number of elements must be the same.
    if (m * n !== r * c) {
        return mat;
    }

    // Create the new reshaped matrix.
    const reshaped: number[][] = Array(r).fill(0).map(() => Array(c).fill(0));

    // Iterate through all elements of the matrix using a single counter.
    // This conceptually flattens the matrix and then rebuilds it.
    for (let i = 0; i < m * n; i++) {
        // Map the 1D index 'i' to 2D indices for both matrices.
        // Original matrix: mat[Math.floor(i / n)][i % n]
        // New matrix: reshaped[Math.floor(i / c)][i % c]
        // Use Math.floor for integer division in TypeScript/JavaScript.
        reshaped[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n];
    }

    return reshaped;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.