File: check-array-formation-through-concatenation/solution.py

Date: 2026-06-06

Time: 15:34

Purpose

This file solves LeetCode 1640: Check Array Formation Through Concatenation. It determines whether a target array arr can be reconstructed by concatenating sub-arrays from pieces in some order, without reordering elements within any piece.

It's a standalone solution module following the repo's convention: one solution.py per problem directory, exporting a single function.

Key Components

canFormArray(arr, pieces) -> bool

The only public function. It checks whether arr can be formed by concatenating elements of pieces in some order.

Contract:

Patterns

Hash-map lookup by first element. The solution exploits the distinctness constraint: since all integers across pieces are unique, each piece can be uniquely identified by its first element. Line 13 builds lookup = {p[0]: p for p in pieces} — a dict mapping each piece's leading value to the full piece. This turns what could be an O(n*m) search into O(1) per position.

Greedy linear scan. The while loop (lines 14-20) walks arr left-to-right with index i. At each position, it finds the piece that must start here (via lookup.get(arr[i])), then verifies the entire piece matches the corresponding slice of arr element-by-element, advancing i as it goes. If it reaches the end, the formation is valid.

Dependencies

Imports: None — pure stdlib Python using only built-in types (list, dict).

Imported by: The test_solution.py in the same directory. The "Imported By" list in the prompt is misleading — those are test files for *other* problems, likely an artifact of the repo's test infrastructure sharing a common runner, not actual imports of this function.

Flow

1. Index pieces — Build {first_element: piece} mapping. O(total elements in pieces).

2. Walk arr — For each position i:

3. Return True if i reaches len(arr).

Time complexity: O(n) where n = len(arr). Each element is visited exactly once. Building the lookup is O(sum of piece lengths), which is at most O(n).

Space complexity: O(n) for the lookup dict.

Invariants

Error Handling

No exceptions are raised. The function communicates failure solely through its False return value, triggered by two conditions:

1. piece is None (line 16) — arr[i] doesn't match any piece's first element.

2. arr[i] != val or i >= len(arr) (line 19) — a matched piece doesn't align with the corresponding slice of arr.

The bounds check i >= len(arr) on line 19 prevents index-out-of-range when a piece extends beyond arr's length.

Topics to Explore

Beliefs