Skip to content

Commit 403c5c4

Browse files
committed
Refactor hasPairWithSum
1 parent 121c7aa commit 403c5c4

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed
Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,30 @@
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:before refactoring O(n²)- after refactoring O(n log n)
5+
* Space Complexity:before refactoring O(1)- after refactoring O(1)
6+
* Optimal Time Complexity:O(n log n)
7+
* https://www.hellointerview.com/learn/code/two-pointers/overview
8+
* The refactored solution first sorts the array, which takes O(n log n) time,
9+
* and then uses the two-pointer technique to scan the array in a single pass (O(n)). The sorting step dominates the overall complexity.
810
* @param {Array<number>} numbers - Array of numbers to search through
911
* @param {number} target - Target sum to find
1012
* @returns {boolean} True if pair exists, false otherwise
1113
*/
1214
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-
}
15+
numbers.sort((a,b)=>a-b);
16+
let left=0;
17+
let right=numbers.length-1;
18+
while (left<right) {
19+
const current_sum=numbers[left]+numbers[right];
20+
if (current_sum === target){
21+
return true;}
22+
if (current_sum<target){
23+
left +=1;
24+
} else {
25+
right -=1;
26+
}
1927
}
2028
return false;
29+
2130
}

0 commit comments

Comments
 (0)