You just watched two pointers, two indices into the list, start one at each end of a sorted list and walk inward. Each sum told them which end to drop, so they found 8 + 13 = 21 in 8 looks.
Quick check
Quick check: Same list, but the target sum is now 34. Which answer does two pointers give?
Why throwing a number out is safe#
Look at the first move. The highlighted cell is right, on 144. left is on 2, at index 0.
2 + 144 = 146, too big. A number is still in play if it sits between the two pointers and has not been thrown out yet. 2 is the smallest number in play, so every sum with 144 is at least 146. No pair with 144 can ever make 21. So 144 is out, and right moves left.
Quick check
Quick check: On the opener list, 2 + 13 = 15 is too small for 21. Can 2 still make 21 with any number right of 13?
That is the mirror rule. If the sum is too small, the number at left is out, because even the biggest number in play cannot lift it to the target. Each number thrown out has no partner left that could work, so the right pair is never thrown away.
The code#
This is the same walk as code, on a shorter list. l and r are the two pointers. Drag the target to 12, a sum no pair makes, and watch l meet r.
target- target = 21
- a = [2, 5, 8, 13, 21, 34]
- l, r = 0, len(a) - 1
- while l < r:
- s = a[l] + a[r]
- if s == target:
- break
- elif s < target:
- l += 1
- else:
- r -= 1
- print([l, r] if l < r else -1)
Variables
- target
- 21 (just changed)
This is the sum we want two numbers to make.
Quick check
Quick check: Set the target to 100. Which pointer does all the moving?
The same walk as a function in Python, C++, C, Java and Go. When there is no pair they return an empty list (C sets both outputs to -1).
How much faster#
Checking every pair needs a loop inside a loop. Two pointers makes one walk: each look moves a pointer one cell closer, so there are at most n - 1 looks.
| List size n | Every pair | Two pointers |
|---|---|---|
| 9 | 36 pairs | at most 8 looks |
| 1,000 | 4,99,500 pairs | at most 999 looks |
| 1 lakh | about 500 crore pairs | at most 99,999 looks |
That is O(n) time against O(n²). The extra space is O(1): just two index variables and a sum, whatever the size.
Quick check
Quick check: Checking every pair also uses O(1) extra space. So what does two pointers gain?
The list must be sorted#
The rule "too big, so drop the right end" works only because the right end holds the biggest number. Shuffle the list and that promise is gone.
Quick check
Quick check: On this shuffled list, the first sum is 13 + 5 = 18, too small. Two pointers drops 13. Is that safe?
Same idea on a word#
A palindrome reads the same both ways, like RACECAR. Put one pointer at each end. If the letters match, move both inward. The first mismatch means it is not a palindrome, and you stop right there.
Play it and watch the two pointers compare letters and move inward together.
For RACECAR that is only 3 comparisons: R with R, A with A, C with C. The middle E has no partner, so it is never checked.
Quick check
Quick check: How many comparisons does the palindrome check make on LEVEL?
Two pointers going the same way#
The third shape: a fast pointer reads every cell, and a slow pointer marks the last value kept. The next new value goes just after it. Here it removes repeats from a sorted list in place, with no second list.
- a = [1, 1, 2, 2, 2, 3]
- slow = 0
- for fast in range(1, len(a)):
- if a[fast] != a[slow]:
- slow += 1
- a[slow] = a[fast]
- print(a[:slow + 1])
Variables
a
A sorted list with repeats.
At the end the list is [1, 2, 3, 2, 2, 3]. Only the first slow + 1 cells matter, and the rest are old leftovers. It is O(n) time and O(1) space.
One last check#
Quick check
Quick check: a = [1, 3, 4, 6, 9], target sum 8. What does the two pointer walk return, and after how many sums?
Next, Two Sum II (Sorted Input): it is this exact walk, except the answer is the positions plus 1, and now you can explain why it never misses a pair.