We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reshape the Matrix

Number: 566

Difficulty: Easy

Paid? No

Companies: MathWorks


Problem Description

Given an m x n matrix and two integers r and c, reshape the matrix into a new matrix with dimensions r x c by taking elements in row-traversing order from the original matrix. If the total number of elements does not match (i.e., if m * n ≠ r * c), return the original matrix.


Key Insights

  • Check if the reshape operation is possible by comparing the total elements (m * n with r * c).
  • Flatten the original matrix while preserving the row-traversing order.
  • Use the flattened list to build the new matrix row by row.
  • If the total number of elements does not match, simply return the original matrix.

Space and Time Complexity

Time Complexity: O(mn) as we iterate through all elements of the matrix once. Space Complexity: O(mn) for the additional list used to store flattened elements (or the new matrix).


Solution

The solution involves first checking whether the reshape is possible by ensuring that the product of the rows and columns of the original matrix equals that of the desired matrix (r * c). If not, the original matrix is returned. Otherwise, the matrix is flattened into a one-dimensional list, preserving the row-order traversal. Finally, the flattened list is segmented by the new column size c to form the reshaped matrix. The primary data structures used include a list (or array) for flattening the matrix and then another list (or vector/array) to hold the final reshaped matrix.


Code Solutions

# Function to reshape the matrix
def matrixReshape(mat, r, c):
    # Calculate the dimensions of the original matrix
    m = len(mat)
    n = len(mat[0])
    
    # Check if reshape is possible
    if m * n != r * c:
        return mat

    # Flatten the original matrix into a list
    flat_list = []
    for row in mat:
        for num in row:
            flat_list.append(num)

    # Create the new matrix by slicing the flat list
    new_matrix = []
    for i in range(0, len(flat_list), c):
        new_matrix.append(flat_list[i:i+c])
    
    return new_matrix

# Example call:
# print(matrixReshape([[1,2],[3,4]], 1, 4))
← Back to All Questions