File: convert-1d-array-into-2d-array/solution.py

Date: 2026-06-06

Time: 15:51

convert-1d-array-into-2d-array/solution.py

Purpose

This file implements LeetCode problem 2022: Convert 1D Array Into 2D Array. It owns both the solution and its test suite in a single module — the standard layout across this repository for self-contained problem implementations.

Key Components

Solution.construct2DArray(original, m, n) -> list[list[int]]

The core algorithm. Takes a flat list and reshapes it into m rows of n columns, returning an empty list if the dimensions don't match the input length.

The implementation uses a single list comprehension that slices original into m consecutive chunks of size n. The slice original[i * n : (i + 1) * n] extracts row i by computing the start and end indices arithmetically — no index tracking or mutation needed.

TestConstruct2DArray — 7 test cases covering:

Patterns

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problems, not actual importers of this module. Each problem directory is self-contained; the list likely reflects a static analysis artifact matching on import unittest across the repo rather than true cross-module dependencies.

Flow

1. Caller invokes construct2DArray(original, m, n).

2. Length check: if len(original) != m * n, return [] immediately.

3. List comprehension iterates i from 0 to m-1, slicing original[i*n : (i+1)*n] to build each row.

4. Returns the list of rows.

The data transformation is purely functional — original is never mutated. Each slice creates a new list, so the output shares no mutable state with the input.

Invariants

Error Handling

There are no exceptions. Invalid inputs (dimension mismatch) produce an empty list [] — the return type doubles as the error signal, per LeetCode convention. The method also handles m=0 or n=0 correctly: if both m*n == 0 and len(original) == 0, the comprehension produces an empty outer list.

Topics to Explore

Beliefs