Find Pair with Given Sum
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests the ability to use hash-based lookups for constant-time complement checking and handle input validation rigorously.
Write a function that determines whether an array contains two elements at different positions that add up to a specified target value.
You are given an array of integers numbers and an integer target_sum. Your task is to return True if there exist two different indices i and j where numbers[i] + numbers[j] == target_sum. If no such pair exists, return False.
Input validation requirements:
- Return
Falseif the input array isNone - Return
Falseif the array contains fewer than two elements - Return
Falseif any element in the array is not a valid integer (including booleans, which should be rejected despite being a subclass ofintin Python)
Additional constraints:
- Do not modify the input array
- Your solution must achieve
O(n)time complexity - Your solution must use
O(n)space complexity
Constraints
0 ≤ len(numbers) ≤ 10^5-10^9 ≤ numbers[i] ≤ 10^9-10^9 ≤ target_sum ≤ 10^9- All elements must be integers (booleans are not valid)
- The same element cannot be used twice (must use two distinct indices)
Examples
Example 1
Input: find_pair_sum([10, 15, 3, 7], 17)
Output: True
Example 2
Input: find_pair_sum([3, 3], 6)
Output: True
Hints
Hint 1
Consider what value would need to pair with each element to reach the target sum
Hint 2
A hash set allows you to check for the existence of a complement in constant time
Hint 3
Process elements in order and check for the complement before adding the current element to your tracking structure
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive solution would examine every possible pair of indices, requiring O(n²) time. We can do better by recognizing that for each element x, we need to find whether target_sum - x exists elsewhere in the array.
The optimal strategy uses a hash set to track elements we've already processed. As we iterate through the array:
- For the current element
x, compute its complement:target_sum - x - Check if this complement exists in our hash set of previously seen values
- If yes, we've found a valid pair at two different indices, so return
True - If no, add the current element to the hash set and continue
The order matters: we check for the complement before adding the current element. This ensures we never match an element with itself, since the set only contains elements from strictly earlier positions.
Input validation must happen upfront. We reject None inputs, arrays with fewer than two elements, and arrays containing non-integer values. Booleans require special handling because in Python, bool is a subclass of int, so we explicitly exclude them with isinstance(value, bool).
Why It Works
When we reach index j and find that target_sum - numbers[j] is in our set, we know some earlier element at index i < j equals this complement. Therefore numbers[i] + numbers[j] == target_sum, and the indices are distinct.
Duplicate values work correctly. For example, with [3, 3] and target 6: when processing the second 3, the first 3 is already in the set, so we detect the match.
No valid pair is missed. If indices i < j form a solution, the check at position j will succeed because numbers[i] was added to the set at position i.
The solution never modifies the input array, satisfying the immutability requirement.
Complexity
Time: O(n) on average. Input validation scans the array once in O(n). The main loop performs n iterations, each doing constant-time hash set operations (lookup and insert). While hash collisions can theoretically degrade performance, this is not a practical concern for integer keys in Python.
Space: O(n). In the worst case where no pair exists, the hash set grows to contain all n elements.
Solution
from typing import List, Optional
def find_pair_sum(numbers: Optional[List[int]], target_sum: int) -> bool:
if numbers is None or len(numbers) < 2:
return False
if any(not isinstance(value, int) or isinstance(value, bool) for value in numbers):
return False
seen = set()
for value in numbers:
if target_sum - value in seen:
return True
seen.add(value)
return False