Find all pairs summing to X
viaLeetCode
Problem Given an array of UNIQUE non-negative integers and target X, return all pairs summing to X.
Input / Output
- Input: int array (distinct values), int X. Output: list of pairs (each pair once; define ordering).
Constraints
- n up to 10^5; O(n) expected.
Example
- arr = [1,4,45,6,10,8], X = 16 → [(6,10)]. With X = 14 → [(4,10), (6,8)].
Expected approach
- Hash set single pass: for each x, if (X − x) already seen → record pair; add x. Uniqueness of values avoids double-count bookkeeping (each pair found once when its second member arrives); self-pair (x = X/2) can't occur without duplicates — say why. O(n)/O(n). Sorted two-pointer alternative: O(n log n), O(1) space, output naturally ordered. Extensions: count pairs with duplicates (frequency map arithmetic), all triplets (3Sum).
asked …