File: reshape-the-matrix/solution.py

Date: 2026-06-06

Time: 18:52

reshape-the-matrix/solution.py

Purpose

This file solves LeetCode 566 - Reshape the Matrix. It owns the single responsibility of converting an m×n matrix into an r×c matrix by reading elements in row-major order, or returning the original matrix unchanged if the reshape is dimensionally impossible.

Key Components

Solution.matrixReshape(mat, r, c) — The sole public method. Contract:

Patterns

Flatten-then-slice: The solution uses the classic 2D reshape idiom — flatten the matrix into a 1D list, then slice it into rows of width c. This is the same conceptual operation as numpy.reshape but implemented with pure list comprehensions.

The flatten step ([val for row in mat for val in row]) produces a row-major traversal. The rebuild step (flat[i*c:(i+1)*c]) partitions it back into chunks of size c.

Dependencies

Imports: None beyond builtins. The solution uses only Python list operations.

Imported by: reshape-the-matrix/test_solution.py directly. The "Imported By" list in the prompt is misleading — those ~400+ test files are unrelated problems that likely share a common test harness or conftest, not actual importers of this module's Solution class.

Flow

1. Extract dimensions m, n from the input matrix.

2. Guard: if total element count m*n != r*c, return mat unchanged — reshape is impossible.

3. Flatten mat into a 1D list flat via nested list comprehension.

4. Slice flat into r rows of c elements each via list comprehension with index arithmetic.

5. Return the new 2D list.

Invariants

Error Handling

There is none beyond the dimension check. The code assumes mat is non-empty and rectangular (guaranteed by LeetCode constraints). If mat were empty or jagged, len(mat[0]) would raise IndexError or produce incorrect results — but that's outside the problem's contract.

Beliefs