Two-Pointer Pair Sum Bug
Spot the pointer-movement mistake in a classic two-pointer sorted-array two-sum solution.
Codejavascript
// arr is sorted ascending; return indices of two values summing to target
function twoSumSorted(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
const sum = arr[left] + arr[right];
if (sum === target) return [left, right];
else if (sum < target) right--;
else left++;
}
return [-1, -1];
}
console.log(twoSumSorted([1, 2, 4, 7, 11], 9)); // expected [1, 3]Why does this two-pointer function fail to find valid pairs?