Reshape the Matrix

Reshape the Matrix (Leet Code-566)

This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 566 . This is a Leet code problem named Reshape the Matrix. We will solve it using python and it is the best space and time-optimized solution. 

Question of 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

Example 1

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output:  [[1,2,3,4]]
 
Reshape the Matrix
Example 2

Input:  mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]
 
. Reshape the Matrix

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Approach to solve Reshape the Matrix

To solve this problem we will traverse through the matrix and while traversing we will create an new matrix of given dimensions. 

Variables and its usage

We will use four variables here to complete our code:

  1. i-  Variable to check the number of elements to be inserted in a row.
  2. arr[] – This list is used to store elements and then inserted into new array as a single row.
  3. new_mat[] – This variable is used to store our new reshaped matrix.
  4. m – Number of rows of matrix.
  5. n – Number of columns of matrix

Algorithm

This method performs the following steps for a given input array:

  1.  Initialize variable i with 0.
  2. Create an empty list arr[].
  3. Initialize variable m and store the number of rows in it.
  4. Initialize variable n and store the number of columns in it.
  5. Now check whether the given elements of the matrix are equal to the elements of the new matrix.
  6.  If yes then go to step 7 otherwise return the old matrix and break.
  7. Now we traverse the matrix.
  8. Repeat steps 9 to 16 for each row.
  9. For each element in a row repeat the step from 10 to.
  10. Add element in arr.
  11. Increment i by 1.
  12. Check whether i is equal to the number of columns of the new matrix.
  13. If yes then follow steps 14,15 and 16.
  14. Add arr in the new_matrix variable.
  15. Initialize arr to blank list.
  16. Initialize i to 0.
  17. Return new_mat.

Python Code for Reshape the Matrix

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        #variable to check number of entries
        i=0
        # array to store columns
        arr=[]
        # to store new matrix
        new_mat = []
        #number of rows
        m = len(mat)
        #number of columns
        n=len(mat[0])
     
        #check wheather both matrix contains same number of elements
        if r*c != m*n:
            #If not then return the given matrix
            return mat
            
        # run for loop for rows 
        for row in mat:
            #run for loop for elements of columns
            for elem in row:
                #add elem value in arr
                arr.append(elem)
                #increment entries pointer
                i+=1                     
                #check i is equal to columns to be entered
                if(i==c):
                    #if yes then add arr list to new_mat 
                    new_mat.append(arr)
                    #reinitilize arr to blank list
                    arr=[]
                    #reinitilize i to 0
                    i=0
                    
        return new_mat
        
                
        

Complexity Analysis

Time Complexity: O(m*n)

Space Complexity: O(m*n)

Leave A Comment

Your email address will not be published. Required fields are marked *