Skip to content

Commit 250a915

Browse files
refactor hasPairWithSum: Replaced nested O(n^2) loops with a one pass Set based approach
1 parent a2582ed commit 250a915

1 file changed

Lines changed: 21 additions & 10 deletions

File tree

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
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) where n is the length of the input array. This is because we iterate through the array once to check for pairs, and each lookup in the Set is O(1) on average. The overall time complexity is linear.
5+
*
6+
*
7+
*
8+
* Space Complexity: O(n) in the worst case, if all numbers in the input array are unique and we end up storing all of them in the Set. The space complexity is linear with respect to the size of the input array.
9+
*
10+
*
11+
*
12+
* Optimal Time Complexity: O(n) because we need to iterate through the array at least once to check for pairs. The use of a Set allows us to achieve this optimal time complexity by providing constant time lookups for the complement values.
713
*
814
* @param {Array<number>} numbers - Array of numbers to search through
915
* @param {number} target - Target sum to find
1016
* @returns {boolean} True if pair exists, false otherwise
1117
*/
1218
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-
}
18-
}
19+
const seenNumbers = new Set();
20+
21+
for (const num of numbers) {
22+
const complement = target - num;
23+
if (seenNumbers.has(complement)) {
24+
return true;
1925
}
20-
return false;
26+
seenNumbers.add(num);
27+
2128
}
29+
30+
return false;
31+
}
32+
console.log(hasPairWithSum([4, 4], 8))

0 commit comments

Comments
 (0)