Reshape the Matrix

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.length

  • n == mat[i].length

  • 1 <= m, n <= 100

  • -1000 <= mat[i][j] <= 1000

  • 1 <= r, c <= 300



My Solution

First off, if the dimensions of the matrices don’t match, we can return the original matrix immediately. Otherwise, we initialize a matrix of size r by c. We then keep track of the row and column by incrementing the column with each element we add. Once the column reaches the column dimension, we increment the row and set column to 0. We do this until we have filled the matrix with all elements and then we just return the matrix.

Time complexity is O(m * n), where m is the number of rows in mat and n is the number of columns in mat. Space complexity is also O(mn) due to the space required for the output matrix.

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

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

        int[][] out = new int[r][c];

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

        return out;
    }
}
Previous
Previous

Subtree of Another Tree

Next
Next

Binary Tree Tilt