1- from typing import List , TypeVar
1+ from typing import List , TypeVar , Set
22
33Number = TypeVar ("Number" , int , float )
44
55
66def has_pair_with_sum (numbers : List [Number ], target_sum : Number ) -> bool :
77 """
88 Find if there is a pair of numbers that sum to a target value.
9+ This uses a hash set (Python's set) to achieve O(N) time complexity.
910
10- Time Complexity:
11- Space Complexity:
12- Optimal time complexity:
11+ Time Complexity: O(N)
12+ Space Complexity: O(N)
13+ Optimal time complexity: O(N)
1314 """
14- for i in range (len (numbers )):
15- for j in range (i + 1 , len (numbers )):
16- if numbers [i ] + numbers [j ] == target_sum :
17- return True
15+ seen_numbers : Set [Number ] = set ()
16+
17+ # Iterate through the list once (O(N) time)
18+ for current_num in numbers :
19+ complement = target_sum - current_num
20+
21+ # Check if the required complement is already in the set (O(1) average time)
22+ if complement in seen_numbers :
23+ return True
24+
25+ # Add the current number to the set for future lookups
26+ seen_numbers .add (current_num )
27+
1828 return False
29+
30+ '''
31+ The complexity is driven by the nested for loops
32+ The bottleneck is the inner loop, which forces us to check every possible pair.
33+ We can use a Hash Set (a set in Python) to store the numbers we've already seen.
34+ This allows us to perform lookups in O(1) average time.
35+
36+ Complexity of Refactor
37+ Time Complexity: O(N)(Linear Time).
38+ The function performs a single pass over the N elements, with constant-time operations inside the loop.
39+ This is the optimal complexity.
40+
41+ Space Complexity:
42+ O(N)(Linear Space). We introduce the seen_numbers set, which, in the worst case,
43+ will store up to N elements from the input list.
44+
45+ '''
0 commit comments