LeetCode 566: Reshape the Matrix Solution

Master LeetCode problem 566 (Reshape the Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

566. Reshape the Matrix

Problem Explanation

Explanation

To reshape the matrix, we need to iterate through the original matrix row by row and fill the elements into a new matrix with the desired number of rows and columns. We can achieve this by using two nested loops. First, we check if the reshape operation is possible by checking if the total number of elements in the original matrix equals the total number of elements in the reshaped matrix. If it is possible, we iterate through the original matrix, keeping track of the current position in the reshaped matrix.

  • Time complexity: O(m * n) where m is the number of rows and n is the number of columns in the original matrix.
  • Space complexity: O(r * c) where r is the number of rows and c is the number of columns in the reshaped matrix.

Solution Code

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

        if (m * n != r * c) {
            return mat;
        }

        int[][] reshaped = new int[r][c];
        int row = 0, col = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                reshaped[row][col] = mat[i][j];
                col++;
                if (col == c) {
                    row++;
                    col = 0;
                }
            }
        }

        return reshaped;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 566 (Reshape the Matrix)?

This page provides optimized solutions for LeetCode problem 566 (Reshape the Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 566 (Reshape the Matrix)?

The time complexity for LeetCode 566 (Reshape the Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 566 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 566 in Java, C++, or Python.

Back to LeetCode Solutions