On a sorted array, a left and right pointer converge — the pair's sum tells you which one to move, finding a target pair in a single pass.
The two-pointers technique puts one marker at each end of a sorted array and walks them toward each other. Because the array is sorted, the current pair's sum tells you exactly which pointer to move: if the sum is too small you need a bigger value, so move the left pointer up; if it's too large you need a smaller value, so move the right pointer down. One linear pass replaces the nested loop a brute-force search would need.
lo at index 0 and hi at the last index.arr[lo] + arr[hi].lo up to a larger value.hi down to a smaller value.lo >= hi) — no pair exists.lo=0(1), hi=5(10): 1 + 10 = 11 > 10 → move hi down.lo=0(1), hi=4(8): 1 + 8 = 9 < 10 → move lo up.lo=1(3), hi=4(8): 3 + 8 = 11 > 10 → move hi down.lo=1(3), hi=3(6): 3 + 6 = 9 < 10 → move lo up.lo=2(4), hi=3(6): 4 + 6 = 10 → found at indices 2 and 3.lo could rescue it, so arr[hi] can never be in any valid pair and is safely discarded. The mirror argument justifies moving lo up when the sum is too small.function pairSum(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo < hi) {
const sum = arr[lo] + arr[hi];
if (sum === target) return [lo, hi];
if (sum < target) lo++; // need a bigger sum
else hi--; // need a smaller sum
}
return null; // no pair
}
// pairSum([1, 3, 4, 6, 8, 10], 10) === [2, 3]