@@ -8,7 +8,7 @@ def has_pair_with_sum(numbers: List[Number], target_sum: Number) -> bool:
88 Find if there is a pair of numbers that sum to a target value.
99
1010 Time Complexity: O(n^2)
11- Space Complexity: O(n). It's memory for the input array arr
11+ Space Complexity: O(n). It's memory for the hash table
1212 Optimal time complexity: O(n)
1313 """
1414 # nested loop result in O(n^2) complexity
@@ -17,20 +17,19 @@ def has_pair_with_sum(numbers: List[Number], target_sum: Number) -> bool:
1717 # if numbers[i] + numbers[j] == target_sum:
1818 # return True
1919 # return False
20-
21- # it's better to use to pointers method here
22- # first: sort the list O(n)
23- numbers = sorted ( numbers )
24- # declare the left and right pointers
25- left , right = 0 , len ( numbers ) - 1
26- # and until we "squeezed" the list check if sum of the pointers is equal to target sum
27- # in worst case we need to do n-1 steps where n is length of the list, so overall complexity will be O(n)
28- while left < right :
29- currentSum = numbers [ left ] + numbers [ right ]
30- if currentSum == target_sum :
20+ # -------
21+ # it's better to use hash table here, where every item can be searched in O(1) time
22+ # create a set
23+ seen_numbers = set ( )
24+ # loop through each element O(n)
25+ for num in numbers :
26+ # calculate the number we need to add to number in a list to get a target sum
27+ complement = target_sum - num
28+ # search hash table for number we need O(1)
29+ # if have seen that number before, then pair found
30+ if complement in seen_numbers :
3131 return True
32- if currentSum > target_sum :
33- right -= 1
34- else :
35- left += 1
36- return False
32+ # add the current number to set
33+ seen_numbers .add (num )
34+ # if the loop completes without finding a pair, return that no pair exists.
35+ return False
0 commit comments