Skip to content

Commit 4cbe96b

Browse files
committed
feat: Optimise hasPairWithSum function
1 parent 69205b2 commit 4cbe96b

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

Lines changed: 10 additions & 7 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)
5+
* Space Complexity:O(1)
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+
const seenNumbers = 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+
// initial solution iterates twice, having outer and inner loop which gives us a time complexity of O(n**2). To optimise this, using a set to store seen numbers, then check whether the complement(target - number) for each num in the array has been seen and in the set. This gives a complexity of O(n)
16+
let complement = target - numbers[i];
17+
18+
if (seenNumbers.has(complement)) {
19+
return true;
1820
}
21+
seenNumbers.add(numbers[i]);
1922
}
2023
return false;
2124
}

0 commit comments

Comments
 (0)