File: can-make-arithmetic-progression-from-sequence/solution.py

Date: 2026-06-06

Time: 15:30

Purpose

This file solves LeetCode 1502: Can Make Arithmetic Progression From Sequence. It determines whether a given list of integers can be rearranged into an arithmetic progression — a sequence where the difference between consecutive terms is constant.

It lives in the standard per-problem directory structure (<problem-slug>/solution.py) and exports a single function consumed by the co-located test file and, notably, by the test files of hundreds of other problems (see "Dependencies" below).

Key Components

can_construct(arr: list[int]) -> bool

The sole public function. Contract:

Patterns

Sort-then-scan: The canonical O(n log n) approach for this problem. Sort the array so the only valid arithmetic progression arrangement is the sorted order itself, then verify the constant-difference property in a single linear pass. This avoids the O(n) math-based alternative (compute expected diff from min/max, check membership via a set) which requires handling duplicates and division edge cases.

Early exit: The loop returns False on the first violation, short-circuiting the scan.

Dependencies

Imports: None — pure stdlib Python.

Imported by: The "Imported By" list in the prompt shows 400+ test files referencing this module. That's a repo-level artifact: the test harness likely imports every solution module uniformly (e.g., via a shared conftest or dynamic import pattern), not because those other problems depend on can_construct at runtime.

Flow

1. arr.sort() — in-place ascending sort.

2. Compute diff = arr[1] - arr[0] — the expected common difference.

3. Iterate i from 2 to len(arr) - 1. For each element, check whether arr[i] - arr[i-1] == diff.

4. If any pair violates the constant difference, return False immediately.

5. If the loop completes, return True.

Invariants

Error Handling

None. The function trusts its caller to provide a list of at least 2 integers, matching the LeetCode problem constraints. No try/except, no input validation. An empty list or single-element list would crash with IndexError at arr[1] - arr[0].

Topics to Explore

Beliefs