-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathhasPairWithSum.js
More file actions
35 lines (30 loc) · 846 Bytes
/
hasPairWithSum.js
File metadata and controls
35 lines (30 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Find if there is a pair of numbers that sum to a given target value.
*
* Time Complexity:Quadratic time
* nested loop so inefficient comparing of each i j to target
* Space Complexity: O(N)
* Optimal Time Complexity: O(N)
*
* @param {Array<number>} numbers - Array of numbers to search through
* @param {number} target - Target sum to find
* @returns {boolean} True if pair exists, false otherwise
*/
export function hasPairWithSum(numbers, target) {
// for (let i = 0; i < numbers.length; i++) {
// for (let j = i + 1; j < numbers.length; j++) {
// if (numbers[i] + numbers[j] === target) {
// return true;
// }
// }
// }
const inventory = {};
for (const num of numbers) {
const needed = target - num;
if (inventory[needed]) {
return true;
}
inventory[num] = true;
}
return false;
}