Count Disjoint Pairs That Add Up to a Goal Value
Arrays & HashingAuto-graded · 22 test casesLast updated
Find the most disjoint pairs in an integer list whose sum equals a goal, using value counts or sorting with two pointers, while handling duplicates, negatives and the half-goal case.
You are given a list of integers values and an integer goal.
In a single move you choose two different positions in the list whose elements add up to exactly goal, and you delete both of those elements. Deleted elements cannot be used again. Positions are what count, so two equal numbers at different positions are two separate elements, but one element can never be paired with itself.
Return the largest number of moves you can make.
Details
- Moves may be made in any order, and the order has no effect on what is allowed. Only which elements end up paired matters.
- Negative numbers and zero are ordinary values.
- If the list has fewer than two elements, the answer is
0. - If
goalis even, elements equal togoal / 2pair with each other, which needs two separate elements per move.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9-2 * 10^9 <= goal <= 2 * 10^9- The function returns a single non-negative integer.
Examples
Example 1
Input: max_goal_pairs([1, 2, 3, 4], 5)
Output: 2
Example 2
Input: max_goal_pairs([3, 1, 3, 4, 3], 6)
Output: 1
Example 3
Input: max_goal_pairs([1, 1, 1, 1], 2)
Output: 2
Example 4
Input: max_goal_pairs([4, -1, 2, 7, -3, 6], 5)
Output: 1
Hints
Hint 1
A value x can only ever be paired with goal - x, so values split into independent groups that do not affect each other.
Hint 2
For two different partner values x and goal - x, the number of moves is limited by the smaller of their counts. When x equals goal - x, each move uses two copies, so think about integer halving of the count.
Hint 3
Scan once while keeping a map of unmatched values seen so far. Check for the partner before inserting the current value, so an element is never paired with itself. Alternatively, sort and move two pointers inward.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A value x can only be paired with goal - x, so the elements split into independent classes {x, goal - x}. Pairs never cross between classes, so the best total is the sum of the best result in each class.
- Two different values (
x != goal - x): each move uses onexand onegoal - x, so at mostmin(cnt[x], cnt[goal - x])moves are possible, and that many can be achieved. - Same value (
x == goal - x): each move uses two copies ofx, so at mostcnt[x] // 2moves are possible.
The reference solution computes this in a single pass with a map unmatched of values still waiting for a partner. For each value v, it looks for goal - v in the map. If a waiting copy exists, it consumes it and counts one move. Otherwise v is added to the map. The lookup happens before the insertion, so an element never pairs with itself.
Why it is correct
- Upper bound: the per-class limits above cannot be exceeded by any strategy, since classes are independent.
- Invariant: for two different partner values
xandy, the map never holds waiting copies of both at once, because a newxwould have matched a waitingyinstead of being stored. So at the end only one side has leftovers, equal to|cnt[x] - cnt[y]|. The number of matches is therefore(cnt[x] + cnt[y] - |cnt[x] - cnt[y]|) / 2 = min(cnt[x], cnt[y]). - Half-goal value: at most one copy waits at any time, so the leftover is
cnt mod 2and the number of matches iscnt // 2.
The greedy therefore reaches the upper bound in every class. Eager matching never hurts because equal values are interchangeable.
Alternative
Sort the list and place one pointer at each end. If the sum equals goal, count a move and shift both pointers inward. If the sum is too small, advance the left pointer. If it is too large, retreat the right pointer. This takes O(n log n) time.
Complexity
- Time: O(n) expected.
- Space: O(n) for the map.
Reference solution
from typing import List
def max_goal_pairs(values: List[int], goal: int) -> int:
# unmatched[v] = how many copies of v are still waiting for a partner
unmatched = {}
moves = 0
for v in values:
partner = goal - v
available = unmatched.get(partner, 0)
if available:
unmatched[partner] = available - 1
moves += 1
else:
unmatched[v] = unmatched.get(v, 0) + 1
return moves