Keep two positions in a sequence and move them toward each other (or the same way) based on what you see, instead of checking every pair.
Used for
target = 10
1 + 11 = 12, too big
1 + 8 = 9, too small
2 + 8 = 10, found
2 + 8 = 10, found
1 + 11 = 12, too small
Sum too small? Too big? That decides which marker can help.
Step 1 of 6
Goal: find two numbers in this sorted list that add up to 10. Trying every pair is slow. Instead, put one marker at each end of the list.
Step 2 of 6
Add the two marked numbers: 1 + 11 = 12. That is more than 10, so the sum is too big.
Step 3 of 6
To make the sum smaller we need a smaller right number, and everything left of 11 is smaller. 11 can never be part of the answer, so cross it out and move the right marker in.
Step 4 of 6
Now 1 + 8 = 9, which is too small. To make it bigger we need a bigger left number, so cross out 1 and move the left marker in.
Step 5 of 6
2 + 8 = 10. Found it. Every move crossed out one number for good, so we look at each number at most once. Two markers closing in on each other is called two pointers, and it works because the list is sorted.
Step 6 of 6
Your turn. The target is now 14. Look at the sum, then choose which marker to move.
function twoSumSorted(a, target) { let l = 0, r = a.length - 1; while (l < r) { const s = a[l] + a[r]; if (s === target) return [l, r]; s < target ? l++ : r--; } return null;}