Code Quiz

Two-Pointer Two Sum Bug

Spot the pointer-movement mistake in this classic two-pointer solution on a sorted array.

Codejavascript
// arr is sorted ascending; return indices of two nums summing to target
function twoSum(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 [];
}

This two-pointer function often fails to find a valid pair. What is the bug?