Skip to content

Commit b99ce99

Browse files
committed
Has pair with sum
1 parent e0fa7e0 commit b99ce99

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

Sprint-1/Python/has_pair_with_sum/has_pair_with_sum.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@ def 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.
99
10-
Time Complexity:
11-
Space Complexity:
12-
Optimal time complexity:
10+
Time Complexity: O(n^2) because we have two nested loops that iterate through the list of numbers.
11+
Space Complexity: O(1)
12+
Optimal time complexity: O(n)
13+
Explanation: The function checks every possible pair of numbers using two nested loops, resulting in O(n^2) time complexity.
14+
Refactor: It uses constant extra space. The optimal solution uses a set to check complements in O(1) time, reducing the overall complexity to O(n).
1315
"""
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
16+
seen = set()
17+
for num in numbers:
18+
complement = target_sum - num
19+
if complement in seen:
20+
return True
21+
seen.add(num)
22+
1823
return False

0 commit comments

Comments
 (0)