Skip to content

Commit 4671058

Browse files
author
Fatma Degirmenci
committed
Refactor hasPairWithSum to use a Set for O(n) lookup
1 parent 902546e commit 4671058

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

‎Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
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:To using nested loop for compare elements time complexity will be ---> O(n*n)
5+
* Space Complexity:We only use few variables -->O(1)
6+
* Optimal Time Complexity:Iterate array only once and use a Set for O(1) lookups / total----->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+
const seen = new Set();
1314
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-
}
15+
const neededNumber = target - numbers[i];
16+
if (seen.has(neededNumber)) {
17+
return true;
18+
} else {
19+
seen.add(numbers[i]);
1820
}
1921
}
2022
return false;

0 commit comments

Comments
 (0)