Pair Sum Existence Check in an Integer List
Arrays & HashingAuto-graded · 24 test casesLast updated
Decide whether any two elements at different positions in an integer list add up to a given value, testing hash-set lookups and careful handling of duplicates.
You are given a list of integers values and an integer goal.
Write a function that returns True if there are two elements at different positions in the list whose sum equals goal, and False otherwise.
Details
- "Different" refers to positions, not numeric values. Two equal numbers that sit at separate indices can form a valid pair. For example,
[3, 3]with a goal of6givesTrue. - A single element cannot be paired with itself. For example,
[3]with a goal of6givesFalse, and[0]with a goal of0givesFalse. - Values may be negative or zero.
- If the list is empty or has only one element, the answer is
False. - The function only needs to return a boolean. It does not need to report which elements were used.
Constraints
0 <= len(values) <= 10^5- Each element of
valuesand the value ofgoalare integers that fit comfortably in standard integer arithmetic (Python integers do not overflow). - The list may contain duplicates and is not guaranteed to be sorted.
- Aim for better than quadratic time.
Examples
Example 1
Input: has_pair_with_sum([2, 7, 11, 15], 9)
Output: True
Example 2
Input: has_pair_with_sum([3, 2, 4], 6)
Output: True
Example 3
Input: has_pair_with_sum([3, 3], 6)
Output: True
Example 4
Input: has_pair_with_sum([1, 2, 3], 7)
Output: False
Hints
Hint 1
For any element x, exactly one other number can complete a pair with it. What is that number in terms of goal and x?
Hint 2
Walk through the list once while remembering the numbers you have already passed. What data structure answers 'have I seen this number?' in constant average time?
Hint 3
Check whether the needed partner is already remembered before you record the current number. This ordering stops an element from pairing with itself while still allowing two equal numbers at different positions to match.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
For each number x, the only partner that can complete the sum is goal - x. Scan the list once from left to right while keeping a set of all numbers seen at earlier positions. At each element:
- If
goal - xis already in the set, an earlier element pairs with the current one, so returnTrue. - Otherwise add
xto the set and move on.
If the scan ends with no match, return False.
Why it is correct
- No false positives: if
goal - xis in the set, it came from an index before the current one, so the two elements are at different positions and sum togoal. - No false negatives: for any valid pair at indices
j < i, the value atjis in the set by the time we reachi, so the check atisucceeds. Every pair is therefore detected when the scan reaches its later element. - No self-pairing:
xis added only after its own check, so a lone element never matches itself, while two equal elements at different positions still do (the first is in the set when the second is checked).
Edge cases follow naturally: an empty or single-element list never triggers a match, [3, 3] with goal 6 returns True, and [0] with goal 0 returns False.
Complexity
- Time: O(n) on average, since each element needs one set lookup and one insertion.
- Space: O(n) in the worst case for the set of seen values.
Alternative
Sort the list and use two pointers from both ends, moving the left pointer up when the sum is too small and the right pointer down when it is too large. This takes O(n log n) time and O(1) extra space if sorting in place, which is useful when memory is tight or the input is already sorted (then it is O(n)).
Reference solution
from typing import List
def has_pair_with_sum(values: List[int], goal: int) -> bool:
seen = set()
for x in values:
# Was the partner needed for x already encountered at an earlier index?
if goal - x in seen:
return True
# Record x only after checking, so it never pairs with itself.
seen.add(x)
return False