Skip to content

Commit c3a6f11

Browse files
committed
Refactor hasPairWithSum using Set
1 parent 0c96de0 commit c3a6f11

1 file changed

Lines changed: 31 additions & 12 deletions

File tree

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,40 @@
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²)
5+
* Space Complexity: O(1)
6+
* Optimal Time Complexity: O(n)
77
*
8-
* @param {Array<number>} numbers - Array of numbers to search through
9-
* @param {number} target - Target sum to find
10-
* @returns {boolean} True if pair exists, false otherwise
8+
* Original complexity:
9+
* The original solution uses nested loops. For each number,
10+
* it checks every remaining number in the array looking for
11+
* a pair whose sum equals the target. Since each number can
12+
* be compared with many other numbers, the time complexity
13+
* is O(n²).
14+
*
15+
* Refactor:
16+
* Use a Set to store numbers that have already been seen.
17+
* For each number, calculate the value needed to reach the
18+
* target and check whether it exists in the Set.
19+
* Set lookups are O(1), so we only need one pass through
20+
* the array.
21+
*
22+
* Refactored Complexity:
23+
* Time Complexity: O(n)
24+
* Space Complexity: O(n)
1125
*/
1226
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-
}
27+
const seen = new Set();
28+
29+
for (const num of numbers) {
30+
const needed = target - num;
31+
32+
if (seen.has(needed)) {
33+
return true;
1834
}
35+
36+
seen.add(num);
1937
}
38+
2039
return false;
21-
}
40+
}

0 commit comments

Comments
 (0)