-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathhasPairWithSum.js
More file actions
33 lines (29 loc) · 884 Bytes
/
hasPairWithSum.js
File metadata and controls
33 lines (29 loc) · 884 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
/**
* Find if there is a pair of numbers that sum to a given target value.
*
* Areas of inefficiency in original version:
* - Nested loops compare every possible pair.
* - This results in quadratic time complexity as input size grows.
*
* Time Complexity: O(n²)
* Space Complexity: O(1)
* Optimal Time Complexity: O(n)
*
* - Use a Set to track numbers seen so far.
* - For each number x, check whether (target - x) has already been seen.
*
* @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) {
const seen = new Set();
for (const num of numbers) {
const complement = target - num;
if (seen.has(complement)) {
return true;
}
seen.add(num);
}
return false;
}