Skip to content

Commit 4db7774

Browse files
committed
Has pair with sum
1 parent b9d4780 commit 4db7774

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
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:
7-
*
4+
* Time Complexity: O(n²)
5+
* Space Complexity: O(1)
6+
* Optimal Time Complexity: O(n)
7+
* Explanation: The function uses a nested loop to check every possible pair of numbers in the array
8+
* to see if they sum up to the target value.
9+
* This results in a time complexity of O(n²) because for each number in the array,
10+
* we are checking it against every other number.
11+
*The refactored version uses a Set to check for the existence of the complement, reducing the overall complexity to O(n).
812
* @param {Array<number>} numbers - Array of numbers to search through
913
* @param {number} target - Target sum to find
1014
* @returns {boolean} True if pair exists, false otherwise
1115
*/
1216
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-
}
17+
const seen = new Set();
18+
for (const num of numbers) {
19+
const complement = target - num;
20+
if (seen.has(complement)) {
21+
return true;
1822
}
23+
seen.add(num);
1924
}
2025
return false;
2126
}

0 commit comments

Comments
 (0)