Skip to content

Commit bdac9fd

Browse files
refactor: use Set for hasPairWithSum to reduce from O(n^2) to O(n)
1 parent 4ab67d6 commit bdac9fd

2 files changed

Lines changed: 22 additions & 15 deletions

File tree

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
11
/**
22
* Find if there is a pair of numbers that sum to a given target value.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
4+
* Time Complexity: O(n^2) - nested loops compare every pair
5+
* Space Complexity: O(1) - no extra data structures
6+
* Optimal Time Complexity: O(n) - using a Set to store seen numbers
77
*
88
* @param {Array<number>} numbers - Array of numbers to search through
99
* @param {number} target - Target sum to find
1010
* @returns {boolean} True if pair exists, false otherwise
1111
*/
1212
export function hasPairWithSum(numbers, target) {
13-
for (let i = 0; i < numbers.length; i++) {
14-
for (let j = i + 1; j < numbers.length; j++) {
15-
if (numbers[i] + numbers[j] === target) {
16-
return true;
17-
}
13+
const seen = new Set();
14+
15+
for (const num of numbers) {
16+
const complement = target - num;
17+
if (seen.has(complement)) {
18+
return true;
1819
}
20+
seen.add(num);
1921
}
22+
2023
return false;
2124
}

‎Sprint-1/Python/has_pair_with_sum/has_pair_with_sum.py‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@ 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) - nested loops compare every pair
11+
Space Complexity: O(1) - no extra data structures
12+
Optimal time complexity: O(n) - using a set to store seen numbers
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+
16+
for num in numbers:
17+
complement = target_sum - num
18+
if complement in seen:
19+
return True
20+
seen.add(num)
21+
1822
return False

0 commit comments

Comments
 (0)