File: minimum-absolute-difference/solution.py

Date: 2026-06-06

Time: 17:51

Purpose

This file solves LeetCode 1200 — Minimum Absolute Difference. Given an array of distinct integers, it finds all pairs of elements whose absolute difference equals the minimum absolute difference across the entire array. It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

minimumAbsDifference(arr: List[int]) -> List[List[int]]

The single exported function. Contract:

Patterns

Sort-then-scan: The solution sorts the array first, which guarantees two things simultaneously: (1) the minimum absolute difference must occur between adjacent elements (no need to check all O(n^2) pairs), and (2) the output pairs are naturally in ascending order without additional sorting.

Two-pass linear scan: Pass 1 computes the minimum difference via min() over adjacent gaps. Pass 2 collects all adjacent pairs matching that minimum. Both are expressed as generator/list comprehensions — idiomatic Python that avoids explicit loops.

Dependencies

Flow

1. Sort in-placearr.sort() mutates the input. O(n log n).

2. Find min difference — Generator expression iterates adjacent pairs arr[i+1] - arr[i] for i in range(len(arr) - 1). Since the array is sorted, all differences are non-negative, so min() yields the minimum absolute difference.

3. Collect matching pairs — List comprehension filters adjacent pairs whose difference equals min_diff, returning them as [arr[i], arr[i+1]]. Because the array is sorted, arr[i] < arr[i+1] is guaranteed, satisfying the a < b output requirement.

Time: O(n log n) dominated by the sort. The two linear scans are O(n).

Space: O(n) for the output list (O(1) auxiliary beyond that, ignoring sort internals).

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. Passing an array with fewer than 2 elements causes an unhandled ValueError from min() on an empty sequence. Passing non-distinct values won't crash but could return pairs with difference 0, which may or may not match the caller's intent.

Topics to Explore

Beliefs