The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
Emma wants two gifts that add up to her 36 dollar card. Trying every pair takes 20 checks; two pointers, walking in from both ends of the sorted prices, takes 6. Why it's safe, how it scales to 10,000 gifts, and how an unsorted list breaks it.
What you will learn
- Explain how two pointers walk in from both ends of a sorted list
- Explain why a dropped item can never be part of the answer
- Compare every-pair O(n squared) with two pointers O(n) on real check counts
- Recognise why two pointers gives a wrong answer on an unsorted list
Before you start
- Python lists and indexes
- Big-O notation
Emma has a gift card worth 36 dollars. The shop has eight gifts, sorted from the cheapest to the dearest: 4, 5, 11, 14, 18, 22, 28 and 35. She wants two gifts that add up to exactly 36. The plain way is to try every pair, and eight gifts make 28 pairs. The answer is 14 plus 22, and two pointers finds it with far fewer checks.
Two friends walk towards each other
Imagine a shelf of gifts, cheapest to dearest. Jack stands at the cheap end and Kate at the dear end, and they want two gifts that make 14 dollars. 1 plus 12 is 13: too little, so Jack steps right, to a dearer gift. 5 plus 12 is 17: too much, so Kate steps left, to a cheaper gift. 5 plus 9 is 14, exactly right.
They never walk back. Jack's side only gets dearer, and Kate's side only gets cheaper. Each step drops one gift for good. That's the two pointers idea.
Why a gift can be dropped
Take Emma's list. Kate starts on 35. Pair 35 with the cheapest gift, 4, and you get 39, already too much. Every other partner is dearer, so every pair with 35 is over 36. Drop it.
Now Jack is on 4, and the dearest gift left is 28. 4 plus 28 is 32, too little. Every other partner is cheaper, so 4 can never reach 36. Drop it.
If the best partner isn't good enough, no partner is. So a dropped gift could never have been part of the answer, and one pass is enough. But this only holds because the list is sorted.
The plain way: every pair
def find(prices, card):
checks = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
checks += 1
if prices[i] + prices[j] == card:
return f"{prices[i]} + {prices[j]} ({checks:,} checks)"
return f"no pair ({checks:,} checks)"
The outer loop picks the first gift, the inner loop pairs it with every gift after it. A loop inside a loop.
The new way: two pointers
def find(prices, card):
left = 0 # Jack: the cheapest gift
right = len(prices) - 1 # Kate: the dearest gift
checks = 0
while left < right:
checks += 1
total = prices[left] + prices[right]
if total == card:
return f"{prices[left]} + {prices[right]} ({checks:,} checks)"
if total > card:
right -= 1 # too much: Kate steps left
else:
left += 1 # too little: Jack steps right
return f"no pair ({checks:,} checks)"
One loop. Every check moves one pointer one step, so eight gifts need at most seven checks.
import every_pair
import two_pointers
prices = [4, 5, 11, 14, 18, 22, 28, 35] # sorted
card = 36 # Emma's gift card
slow = every_pair.find(prices, card)
fast = two_pointers.find(prices, card)
print("Every pair: " + slow)
print("Two pointers: " + fast)
Every pair: 14 + 22 (20 checks)
Two pointers: 14 + 22 (6 checks)
Step by step
| Check | left + right | Sum | Move |
|---|---|---|---|
| 1 | 4 + 35 | 39, too much | right - 1 (35 dropped) |
| 2 | 4 + 28 | 32, too little | left + 1 (4 dropped) |
| 3 | 5 + 28 | 33, too little | left + 1 |
| 4 | 11 + 28 | 39, too much | right - 1 |
| 5 | 11 + 22 | 33, too little | left + 1 |
| 6 | 14 + 22 | 36 | found |
Ten thousand gifts
import every_pair
import two_pointers
for n in (100, 1_000, 10_000):
prices = [0] * n
for i in range(n):
prices[i] = i + 1 # 1, 2, 3 ... n: sorted
card = n + (n - 1) # only the two dearest fit
print(f"{n:>6,} gifts every pair: {every_pair.find(prices, card)}")
print(f"{n:>6,} gifts two pointers: {two_pointers.find(prices, card)}")
100 gifts every pair: 99 + 100 (4,950 checks)
100 gifts two pointers: 99 + 100 (99 checks)
1,000 gifts every pair: 999 + 1000 (499,500 checks)
1,000 gifts two pointers: 999 + 1000 (999 checks)
10,000 gifts every pair: 9999 + 10000 (49,995,000 checks)
10,000 gifts two pointers: 9999 + 10000 (9,999 checks)
Ten times more gifts means about a hundred times more checks for every pair, but only ten times more for two pointers.
Breaking it: a mixed-up list
import every_pair
import two_pointers
prices = [4, 11, 5, 28, 14, 22, 18, 35] # NOT sorted
card = 36
slow = every_pair.find(prices, card)
fast = two_pointers.find(prices, card)
print("Every pair: " + slow)
print("Two pointers: " + fast)
Every pair: 14 + 22 (23 checks)
Two pointers: no pair (7 checks)
Two pointers trusts the order. It assumes everything Jack passed was cheaper and everything Kate passed was dearer. Here that isn't true, so at one point Kate steps left and drops 22, half of the answer, and the pointers meet with "no pair". That's wrong. Every pair doesn't care about order and still finds 14 plus 22. Two pointers works only on a sorted list. Sort first, for example with sorted(), but sorting costs more than the walk itself, so the technique pays off best on a list that's already in order.
What it costs
| Approach | Checks for 8 gifts | Cost | Needs sorted list? |
|---|---|---|---|
| Every pair | up to 28 | O(n²) | no |
| Two pointers | at most 7 | O(n) | yes |
Where you meet it
- Two items that fit a budget on a sorted price list, like Emma's.
- Checking a word that reads the same backwards, like "level": compare first and last, then walk in.
- Reversing a word: swap the two ends, then walk in until they meet.
- Merging two sorted piles: a marker at the front of each, always take the smaller card.
Different places, one idea: two markers that only ever move one way. A close relative is the sliding window, where both markers move the same way.
Try it yourself
Change the card to 33 and count how many checks two pointers needs.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
