← back

Reshape Matrix

#3 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Reshape a given matrix into a specified new shape. If the total number of elements does not match the product of the new dimensions, return a list containing [-1].

Solution

1
2
3
4
5
6
def reshape_matrix(a: list[list[int|float]], new_shape: tuple[int, int]) -> list[list[int|float]]:
    flat = [elem for row in a for elem in row]
    new_rows, new_cols = new_shape
    if len(flat) != new_rows * new_cols:
        return [[-1]]
    return [flat[i * new_cols:(i + 1) * new_cols] for i in range(new_rows)]

Explanation

  1. Flatten the original matrix into a single list of elements.
  2. Check that the total element count equals new_rows * new_cols.
  3. Slice the flat list into chunks of new_cols to form each row of the reshaped matrix.

Complexity

  • Time: O(m n) where m n is the total number of elements
  • Space: O(m * n) for the flattened list and the result