Skip to content

Commit 6d6b1f6

Browse files
committed
perf(py): optimize has_pair_with_sum (O(n²) → O(n))
1 parent 3bc70df commit 6d6b1f6

File tree

1 file changed

+42
-6
lines changed

1 file changed

+42
-6
lines changed

Sprint-1/Python/has_pair_with_sum/has_pair_with_sum.py

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,48 @@ 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) - Single pass through the list
11+
Space Complexity: O(n) - Set to store seen numbers
12+
Optimal Time Complexity: O(n) - Cannot do better than linear time
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:
14+
# OPTIMIZED IMPLEMENTATION: O(n) time complexity
15+
# Previous implementation: O(n²) due to nested loops
16+
17+
seen = set() # O(n) space for storing seen numbers
18+
19+
# Single pass through list: O(n) time complexity
20+
for num in numbers:
21+
complement = target_sum - num
22+
23+
# Check if complement exists in seen numbers: O(1) lookup
24+
if complement in seen:
25+
return True
26+
27+
# Add current number to seen set: O(1) operation
28+
seen.add(num)
29+
30+
return False
31+
32+
# ORIGINAL IMPLEMENTATION (for comparison):
33+
"""
34+
def has_pair_with_sum(numbers: List[Number], target_sum: Number) -> bool:
35+
for i in range(len(numbers)): # O(n) iterations
36+
for j in range(i + 1, len(numbers)): # O(n) iterations each
37+
if numbers[i] + numbers[j] == target_sum: # O(1) comparison
1738
return True
1839
return False
40+
41+
COMPLEXITY ANALYSIS OF ORIGINAL:
42+
- Outer loop: O(n) iterations
43+
- Inner loop: O(n) iterations for each outer iteration
44+
- Total: O(n²) time complexity
45+
- Space: O(1) - only using loop variables
46+
47+
PERFORMANCE ISSUES:
48+
- Quadratic time complexity O(n²)
49+
50+
IMPROVEMENTS MADE:
51+
1. Reduced from O(n²) to O(n) time complexity
52+
2. Single pass through list instead of nested loops
53+
3. Set lookup is O(1) vs nested iteration O(n)
54+
"""

0 commit comments

Comments
 (0)