Count Maximum Disjoint Pairs Summing to a Target
Arrays & HashingAuto-graded · 22 test casesLast updated
Find the most index-disjoint pairs in an integer array whose values add up to a target, testing hashing of complements, counting, and handling of the self-pairing case.
Count Maximum Disjoint Pairs Summing to a Target
You are given a list of integers values and an integer target.
A move picks two different positions i and j in the list such that values[i] + values[j] == target, and then takes both of those positions out of play. A position that has been taken out cannot be used in any later move, so every position belongs to at most one move.
Return the largest possible number of moves that can be made.
Details
- Only the values matter, not where they sit in the list. Any two distinct positions may be paired, regardless of which one comes first.
- A single position can never be paired with itself. For example, if
targetis6and the list holds just one3, that3has no partner. - If
targetis even, copies oftarget / 2can be paired with one another, but each copy still serves in at most one pair. - Values may be negative or zero.
- If no valid pair exists (including when the list is empty or has one element), return
0.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9-2 * 10^9 <= target <= 2 * 10^9- The input list may be modified or left untouched; only the returned integer is checked.
Examples
Example 1
Input: max_pairs_with_sum([1, 2, 3, 4], 5)
Output: 2
Example 2
Input: max_pairs_with_sum([3, 1, 3, 4, 3], 6)
Output: 1
Hints
Hint 1
Does the order of the elements matter, or only how many copies of each value exist?
Hint 2
A value v can only be matched with the value target - v. Think about how many pairs a group of v's and a group of target - v's can produce, and treat the case v == target - v separately.
Hint 3
Scan once while keeping a table of unmatched values. For each element, first check whether its complement is waiting in the table; only if not, add the element itself to the table.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because any two distinct positions may be paired, the order of the list is irrelevant. A copy of value v can only ever be matched with a copy of target - v, so the values split into independent classes {v, target - v}.
- If
v != target - v, the class yields at mostmin(count[v], count[target - v])pairs. - If
v == target - v(only whentargetis even andv = target / 2), the class yields at mostcount[v] // 2pairs.
The answer is the sum of these quantities over all classes, each counted once.
To avoid computing counts in a separate pass, scan the list once while keeping a dictionary of unmatched values:
- For the current value
v, computeneed = target - v. - If an unmatched copy of
needis waiting, consume it and add one to the answer. - Otherwise, store
vas unmatched.
Why it is correct
Upper bound. Every move uses one v and one target - v, so no class can exceed the bounds above, and classes do not interact.
The scan reaches the bound. For a class with two different values v and w, the waiting table never holds copies of both at once: whichever arrives second would have matched the waiting one instead of being stored. Hence every copy of the less frequent value finds a partner, giving exactly min(count[v], count[w]) pairs. For the self-paired value, copies alternate between being stored and being matched, giving count // 2. Checking for the complement before inserting is what prevents an element from pairing with itself.
Since the scan meets the upper bound in every class, it is optimal.
Complexity
- Time: O(n) expected, one pass with hash map operations.
- Space: O(n) for the table of unmatched values.
An alternative is to sort and use two pointers (move the left pointer up when the sum is too small, the right pointer down when too large, and count and move both on equality). That takes O(n log n) time and little extra space.
Reference solution
from typing import List
def max_pairs_with_sum(values: List[int], target: int) -> int:
waiting = {} # value -> number of unmatched copies seen so far
moves = 0
for v in values:
need = target - v
if waiting.get(need, 0) > 0:
waiting[need] -= 1
moves += 1
else:
waiting[v] = waiting.get(v, 0) + 1
return moves