Skip to content

Commit c7303ce

Browse files
committed
Refactor hasPairWithSum using Set for O(n) lookup
1 parent 92c44a0 commit c7303ce

1 file changed

Lines changed: 47 additions & 9 deletions

File tree

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,59 @@
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(n)
6+
* Optimal Time Complexity: O(n)
7+
*
8+
* The original solution used nested loops, resulting in O(n²) time.
9+
* This version uses a Set to store previously seen numbers,
10+
* allowing constant-time lookups.
11+
*
12+
* @param {Array<number>} numbers - Array of numbers to search through
13+
* @param {number} target - Target sum to find
14+
* @returns {boolean} True if pair exists, false otherwise
15+
*/
16+
export function hasPairWithSum(numbers, target) {
17+
const seen = new Set();
18+
19+
for (const number of numbers) {
20+
const complement = target - number;
21+
22+
if (seen.has(complement)) {
23+
return true;
24+
}
25+
26+
seen.add(number);
27+
}
28+
29+
return false;
30+
}/**
31+
* Find if there is a pair of numbers that sum to a given target value.
32+
*
33+
* Time Complexity: O(n)
34+
* Space Complexity: O(n)
35+
* Optimal Time Complexity: O(n)
36+
*
37+
* The original solution used nested loops, resulting in O(n²) time.
38+
* This version uses a Set to store previously seen numbers,
39+
* allowing constant-time lookups.
740
*
841
* @param {Array<number>} numbers - Array of numbers to search through
942
* @param {number} target - Target sum to find
1043
* @returns {boolean} True if pair exists, false otherwise
1144
*/
1245
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-
}
46+
const seen = new Set();
47+
48+
for (const number of numbers) {
49+
const complement = target - number;
50+
51+
if (seen.has(complement)) {
52+
return true;
1853
}
54+
55+
seen.add(number);
1956
}
57+
2058
return false;
21-
}
59+
}

0 commit comments

Comments
 (0)