Skip to content

Commit 4d26911

Browse files
author
Fatma Degirmenci
committed
Refactor has_pair_with_sum to use a set for O(n) lookup
1 parent 0ebc392 commit 4d26911

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

Sprint-1/Python/has_pair_with_sum/has_pair_with_sum.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ 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: We have nested loop --> O(n*n)
11+
Space Complexity:We have variables -->O(1)
12+
Optimal time complexity:We can use only one loop -->O(n)
1313
"""
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
14+
seen = set()
15+
for num in numbers:
16+
if target_sum - num in seen:
17+
return True
18+
seen.add(num)
1819
return False

0 commit comments

Comments
 (0)