Two sum (sorted, two pointers)
Given a sorted array of integers nums and a target, determine whether a pair of numbers in it sums to that target, and report their positions rather than the numbers themselves.
Examples
Example 1
- Input
- nums = [1, 3, 4, 5, 7, 11]target = 9
- Output
- 4 + 5 = 9, and the 4 and the 5 sit at positions 2 and 3.
[2,3]
Example 2
- Input
- nums = [1, 3, 4, 5, 7, 11]target = 100
- Output
- Even 11 + 7, the largest pair, is only 18 — no pair reaches 100.
[-1,-1]
The Code
function twoSum(nums, target) {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const sum = nums[lo] + nums[hi];
if (sum === target) return [lo, hi];
if (sum < target) lo++;
else hi--;
}
return [-1, -1];
}
twoSum([1, 3, 4, 5, 7, 11], 9);Explanation
Every step throws away a set of pairs rather than testing one: too big means the larger number cannot be in any answer, too small means the smaller one cannot be, and the search closes in from both ends.
- 1
Because the array is sorted, the pairs can be searched without looking at all of them. Start with the two ends —
loon the smallest number,hion the largest — which is the largest sum any pair can have.lo1031425374hi1151 + 11 = 12 > 9
- 2
If 11 is already too big beside the smallest number in the array, it is too big beside every other one as well, so every pair using 11 can be dropped at once.
histeps back to 7.lo10314253hi741151 + 7 = 8 < 9
- 3
The same argument the other way round: if 1 cannot reach 9 even beside the largest number left, no pair using 1 ever will, so every pair using 1 goes too.
losteps forward to 3.10lo314253hi741153 + 7 = 10 > 9
- 4
Over the target, so the larger number goes:
histeps back to 5.10lo3142hi53741153 + 5 = 8 < 9
- 5
Under the target, so the smaller number goes:
losteps forward to 4 — and the pair lands on the target. The answer is the positions those two sit at, 2 and 3. Had the pointers met without ever matching, there would have been no pair to find.1031lo42hi53741154 + 5 = 9
More like this
All two pointers examples (9) →- Reverse array Swap the ends and step inward until the pointers meet.
- Most water Widest gap first; always move the shorter wall inward.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.
- Remove duplicates A fast reader and a slow writer compact the array in place.