Skip to content

Commit 6c5bcf5

Browse files
refactor: optimize hasPairWithSum from O(n^2) time, O(1) space to O(n) time, O(n) space using Set
1 parent ff591c0 commit 6c5bcf5

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed
Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
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)
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+
if (seen.has(target - num)) {
17+
return true;
1818
}
19+
seen.add(num);
1920
}
21+
2022
return false;
2123
}

0 commit comments

Comments
 (0)