Skip to content

Commit 04854fa

Browse files
answered Python has pair with sum exercise
1 parent 8e24202 commit 04854fa

File tree

3 files changed

+61
-8
lines changed

3 files changed

+61
-8
lines changed
Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,45 @@
1-
from typing import List, TypeVar
1+
from typing import List, TypeVar, Set
22

33
Number = TypeVar("Number", int, float)
44

55

66
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.
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+
'''

Sprint-1/Python/has_pair_with_sum/package-lock.json

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"dependencies": {
3+
"pytest": "^1.0.0"
4+
}
5+
}

0 commit comments

Comments
 (0)