Two pointers from both ends
After this: Find a pair in a sorted array in one pass, and explain why every move is safe.
On this page · 10 sections · 4 checks
In the last lesson, trying every pair of [1, 3, 5, 8, 11] took eight tries to find 5 + 8 = 13. This lesson finds the same pair in four tries, and it never needs more tries than the array has numbers.
The new method depends on one fact: the array is . That means the numbers go from smallest to largest, so the smallest is at index 0 and the largest is at the last index.
Put your left finger on the smallest number and your right finger on the largest. In code, these two fingers are two pointers: left starts at index 0, and right starts at the last index.
One step, in detail
left is on 1 and right is on 11. The sum is 1 + 11 = 12. The target is 13, so the sum is too small. One of the pointers must move. Which one?
Look at every pair that uses the 1.
| Pair | Sum |
|---|---|
| 1 + 3 | 4 |
| 1 + 5 | 6 |
| 1 + 8 | 9 |
| 1 + 11 | 12 |
All four sums are below 13. The largest of them is 1 + 11, because 11 is the largest number in the array. So we have learned something for certain: the 1 is not part of any pair that adds up to 13.
That means we can stop thinking about the 1. We move left one cell to the right, onto the 3.
We call this move safe. A safe move leaves behind only a number that cannot be in the answer, so the move cannot lose the answer.
Moving right would not be safe. It would leave the 11 behind, and we have not ruled out the 11. It would also make the sum smaller, when we need it to be bigger.
The other direction
Now left is on 3 and right is on 11. The sum is 3 + 11 = 14, which is too big.
The 1 is already ruled out, so look at the pairs that use the 11 and the numbers still between the pointers: 3 + 11 = 14, 5 + 11 = 16 and 8 + 11 = 19. All of them are above 13. The smallest of them is 3 + 11, because 3 is the smallest number left. So the 11 is not part of any pair that adds up to 13, and we move right one cell to the left, onto the 8.
All four steps
- 1 + 11 = 12. Too small, so
leftmoves to 3. - 3 + 11 = 14. Too big, so
rightmoves to 8. - 3 + 8 = 11. Too small, so
leftmoves to 5. - 5 + 8 = 13. Found, at indexes 2 and 3.
The rule
Here is the rule in general. Add the two numbers under the pointers and compare the sum with the target.
- Too small: move
leftone cell to the right.nums[right]is the largest number still between the pointers, so every pair that usesnums[left]is too small as well. - Too big: move
rightone cell to the left.nums[left]is the smallest number still between the pointers, so every pair that usesnums[right]is too big as well. - Equal: stop. You have found the pair.
If the two pointers meet on the same cell, stop as well. A pair needs two different cells, so there is no pair.
Why this is fast
Each comparison rules out one number for good. The pointers only ever move towards each other, and they stop when they meet. So an array of n numbers needs at most n − 1 comparisons. This is one trip along the array, which programmers call one .
| Numbers | Two pointers, at most | Trying every pair, at most |
|---|---|---|
| 5 | 4 | 10 |
| 1,000 | 999 | 499,500 |
The cost is O(n), which means that the work grows at the same rate as the array. See Counting steps if you want a reminder.
One sentence holds the whole method together: if a pair with the right sum exists, it is still at or between the pointers. This is true at the start, when the pointers are at the two ends. Every safe move keeps it true. A fact that stays true at every step of a loop is called an .
The code
def two_sum_sorted(nums, target): left, right = 0, len(nums) - 1 comparisons = 0 while left < right: comparisons += 1 total = nums[left] + nums[right] if total == target: return left, right, comparisons if total < target: left += 1 # too small: only a bigger left value can help else: right -= 1 # too big: only a smaller right value can help return -1, -1, comparisons
i, j, comparisons = two_sum_sorted([1, 3, 5, 8, 11], 13)print(i, j, comparisons)i, j, comparisons = two_sum_sorted([1, 3, 5, 8, 11], 7)print(i, j, comparisons)2 3 4 -1 -1 4
public class Main { static int[] twoSumSorted(int[] nums, int target) { int left = 0, right = nums.length - 1; int comparisons = 0; while (left < right) { comparisons++; int total = nums[left] + nums[right]; if (total == target) return new int[] {left, right, comparisons}; if (total < target) left++; // too small: only a bigger left value can help else right--; // too big: only a smaller right value can help } return new int[] {-1, -1, comparisons}; }
public static void main(String[] args) { int[] hit = twoSumSorted(new int[] {1, 3, 5, 8, 11}, 13); System.out.println(hit[0] + " " + hit[1] + " " + hit[2]); int[] miss = twoSumSorted(new int[] {1, 3, 5, 8, 11}, 7); System.out.println(miss[0] + " " + miss[1] + " " + miss[2]); }}2 3 4 -1 -1 4
Here is how to read it.
leftandrightstart at the two ends.comparisonsis a counter we added to measure the cost.- The loop runs while
left < right, which means while the pointers are on two different cells and have not met. - The highlighted lines are the two moves from the rule.
- If the loop ends with no match, the function returns −1 for both indexes, as the brute force did.
The first output line is the search for 13, the four steps you saw above. The second line is a target that no pair reaches, 7.
- 1 + 11 = 12. Too big, so
rightmoves to 8. - 1 + 8 = 9. Too big, so
rightmoves to 5. - 1 + 5 = 6. Too small, so
leftmoves to 3. - 3 + 5 = 8. Too big, so
rightmoves to 3.
Now both pointers are on the same cell, so the loop ends after four comparisons. Trying every pair needed all ten.
Watch it happen
The first run asks you to tap a cell before it starts. After that, read why each pointer moves before you go to the next step.
- Two pointers: sum 13The target is 13. Read why each pointer moves before you go to the next step.
- Two pointers: sum 7
- 01
- 13
- 25
- 38
- 411
Run an operation to begin.
When the array is not sorted
The rule needs the array to be sorted. Without that, the numbers at the ends are not the largest and the smallest, so a move is not safe. Here is what goes wrong with [3, 11, 1, 8, 5] and target 13.
- 3 + 5 = 8. Too small, so
leftmoves to 11. - 11 + 5 = 16. Too big, so
rightmoves to 8. This leaves the 5 behind, and the 5 is part of the answer. It was ruled out only because 11 looked like the smallest number left, and it is not. - 11 + 8 = 19. Too big, so
rightmoves to 1. - 11 + 1 = 12. Too small, so
leftmoves to 1.
The pointers have met, and the code says there is no pair. But 5 + 8 = 13 is in the array.
So you have two choices if the array is not sorted.
- Sort it first. A good sort takes O(n log n) steps. Here log n is about the number of times you can cut n in half before you reach 1. For 1,000 numbers that is about 10, so O(n log n) is about 1,000 × 10 steps. That is more than O(n), but far less than O(n²). This cost must be counted, so the total is O(n log n).
- Use a hash map instead. Keep a map of the numbers seen so far, and ask for each new number whether its partner is already there. This takes O(n) steps on average, with no sorting. It is the idea of the seen set from hash maps in practice.
Check yourself
The pointers are on 1 and 11. The sum is 12 and the target is 13. Why is it safe to move left, so that no answer can be lost?
Complete the too-small case. The sum needs to get bigger, and only one pointer can make it bigger.
def two_sum_sorted(nums, target): left, right = 0, len(nums) - 1 while left < right: total = nums[left] + nums[right] if total == target: return left, right if total < target: ______________________ # ← too small: which pointer moves, and which way? else: right -= 1 return -1, -1static int[] twoSumSorted(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left < right) { int total = nums[left] + nums[right]; if (total == target) return new int[] {left, right}; if (total < target) { ______________________ // ← too small: which pointer moves, and which way? } else { right--; } } return new int[] {-1, -1};}Same array, [1, 3, 5, 8, 11], with target 16. Where are the pointers after two comparisons, and when is the pair found?
The numbers are not sorted. What does finding a pair with two pointers cost now?
Connect
- Put left and right at the two ends of a sorted array, and move the one that the sum tells you to move.
- Explain why a move is safe: the number left behind cannot be in any remaining pair.
- Say why the pass is O(n): the pointers only move inward, at most n − 1 comparisons. Sorting first adds O(n log n).