
The two pointer technique finds two numbers in a sorted list that add up to a target. Put a pointer (a position marker) at each end and add them. Too small? Move the left pointer right. Too big? Move the right pointer left. Each check rules out one number, so n numbers take at most n − 1 checks.
In this post we start with a famous puzzle about birthdays, to see how fast the number of pairs grows. Then we check every pair the slow way, find out why two pointers can rule out a number with one sum, and trace them by hand. We write it in Python and JavaScript, count both versions on 1,000 prices, and use the same trick to spot palindromes, reverse a list and join database tables.
A few words first. A sorted list is in order, smallest first. An index is a position in a list, counting from 0. A pointer, in this post, is just a variable that holds an index, so it "points at" one item. Ours are called lo and hi, short for low and high. A check is one sum of two prices, compared with the target.
Key takeaways
- Pairs grow fast: n items make n(n − 1)/2 pairs. 23 people make 253 pairs; 1,000 prices make 499,500. Checking every pair is O(n²).
- Start at both ends of a sorted list:
loon the smallest item,hion the biggest. - Too small? The smallest item can't be in any pair that makes the target, because even the biggest item isn't enough. Move
loright. Too big? The biggest item can't be in any pair that makes the target. Movehileft. - Each check moves one pointer one step, so n items take at most n − 1 checks: O(n). On 1,000 prices with no matching pair, we counted 499,500 checks the slow way and 999 with two pointers.
while lo < hi, not<=: the pointers must never land on the same item, or one item gets counted twice.- The list must be sorted. If it isn't, sort it first (O(n log n)), or use a set (a collection with no repeats) and skip the sort.
- The same idea checks palindromes, reverses a list in place, and lets a database join two sorted tables in one pass.
This post goes with letsBug Code, episode 9. Watch it first, or read on: everything in the video is here, plus every code sample with its real output, and practice questions with answers.
Why are pairs so slow to check?
Because there are far more pairs than items. Here's a famous puzzle, called the birthday problem. How many people do you need in a room for a chance of more than one in two that two of them share a birthday? Only 23. Wikipedia says: "In a group of 23 people, the probability that at least two share a birthday is 50.7%." (A probability is a chance, here just over a half.)
That sounds far too high, until you count the pairs. Each of the 23 people can pair with 22 others. That counts every pair twice (Ava with Ben, and Ben with Ava), so halve it: 23 × 22 / 2 = 253 pairs, and each pair is a chance of a match. Wikipedia makes the same point: the birthday comparisons are made "between every possible pair of individuals."
The same sum works for any list. n items make n(n − 1)/2 pairs. A shop with 1,000 prices has 1,000 × 999 / 2 = 499,500 pairs, nearly half a million. Now say you have a gift card, and you want two items that cost exactly what's on it. Checking every pair is slow. But if the prices are sorted, there's a trick that needs fewer than 1,000 checks.
How slow is a nested loop for pair sum?
Here's the shop: eight prices, in pounds, already sorted. 1, 3, 4, 6, 8, 11, 14, 17. Your gift card is worth £22. The obvious code checks every pair, with a loop inside a loop, called a nested loop:
def every_pair(prices, target):
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
if prices[i] + prices[j] == target:
return prices[i], prices[j]
return None
print(every_pair([1, 3, 4, 6, 8, 11, 14, 17], 22))
(8, 14)
The outer loop picks the first price, prices[i]. The inner loop tries it with every price after it, prices[j]. Starting j at i + 1 means no price pairs with itself, and no pair is tried twice. Then the outer loop moves on to the second price, and so on.
It finds 8 and 14 after 24 checks. With a gift card of £16, no pair matches, so it tries all 28 pairs: 8 × 7 / 2 = 28. For n prices that's n(n − 1)/2 checks, which is O(n²): double the list, and the work goes up about four times. It's the same triangle of comparisons as bubble sort, from the bubble sort and insertion sort post.
Databases have a name for this slow way, too. When a database joins two tables (matches up their rows), one option is the nested loop join, a loop inside a loop. The PostgreSQL docs say: "The right relation is scanned once for every row found in the left relation. This strategy is easy to implement but can be very time consuming." (A relation is a table. To implement something means to write the code for it.)
How does the two pointer technique work?
It uses the order. Put one pointer, lo, on the cheapest price, and another, hi, on the most expensive. Add them: 1 + 17 = 18. That's too small for £22.
Here's the key step. 17 is the biggest price there is, so 1 plus any other price is even smaller than 18. That means 1 can't be in any pair that makes 22. Cross it out, and move lo one step right.
If the sum is too big, it works the other way round. The smallest price left is already in the sum, so the biggest price plus anything else would be even bigger. The biggest price can't be in any pair that makes 22: cross it out, and move hi one step left.
So every check either finds the pair or crosses out one price, and that price never comes back. That's why the pointers can never skip the answer: everything they move past is a price that couldn't be in any pair that makes 22.
How do you trace two pointers on a sorted list?
With a table: one row per check. Too small moves lo right, and too big moves hi left. Here's the gift card of £22 again:
| lo | hi | Sum | Result |
|---|---|---|---|
| 1 | 17 | 18 | too small |
| 3 | 17 | 20 | too small |
| 4 | 17 | 21 | too small |
| 6 | 17 | 23 | too big |
| 6 | 14 | 20 | too small |
| 8 | 14 | 22 | found |
Found it: 8 and 14, in 6 checks instead of 24. The lo and hi columns show the prices the pointers are on, not their indexes.

Another way to see why it can't miss: draw every pair as a square in a grid, with the cheaper price down the side and the more expensive one along the top. That's 28 squares. Each time lo moves, a whole row of pairs is ruled out. Each time hi moves, a whole column is. Two pointers walk to the answer and look at only 6 squares.

How do you write two pointers in Python?
With one while loop. lo and hi are the two pointers, starting at both ends:
def pair_sum(prices, target):
lo, hi = 0, len(prices) - 1
while lo < hi:
total = prices[lo] + prices[hi]
if total == target:
return prices[lo], prices[hi]
if total < target:
lo += 1
else:
hi -= 1
return None
prices = [1, 3, 4, 6, 8, 11, 14, 17]
print(pair_sum(prices, 22))
print(pair_sum(prices, 16))
(8, 14)
None
Line by line:
lostarts at index 0, the first price.histarts atlen(prices) - 1, the last index. Eight prices have indexes 0 to 7.- While
lois left ofhi, add the two prices. - If the total equals the target, return the pair. Returning two values gives a tuple, a pair of values in round brackets.
- Too small?
logoes up by one. Too big?hicomes down by one. - If the pointers meet, there's no pair, so return
None, Python's value for "nothing".
With a gift card of £16, no two prices make it. Two pointers say None after 7 checks.
Notice lo < hi. The pointers never land on the same price, so the code can't spend the one £8 item twice. That's the video's challenge, in the practice questions below.
Why is the two pointer technique O(n)?
Because each check moves one pointer one step inward. The pointers start n − 1 steps apart, and the loop stops when they meet. So it takes at most n − 1 checks, which is O(n): double the list, and the work only doubles. (The Big O notation post explains what O(n) and O(n²) mean.)
Let Python count. These versions of both functions add 1 to checks on every sum. global checks lets each function change the checks that lives outside it:
import random
checks = 0
def every_pair(prices, target):
global checks
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
checks += 1
if prices[i] + prices[j] == target:
return prices[i], prices[j]
return None
def pair_sum(prices, target):
global checks
lo, hi = 0, len(prices) - 1
while lo < hi:
checks += 1
total = prices[lo] + prices[hi]
if total == target:
return prices[lo], prices[hi]
if total < target:
lo += 1
else:
hi -= 1
return None
prices = sorted(random.Random(4).sample(range(2, 200_000, 2), 1000))
for find in (every_pair, pair_sum):
checks = 0
print(find(prices, 100_001), f"{checks:,}")
None 499,500
None 999
The prices are 1,000 different even numbers below 200,000, picked at random and then sorted. range(2, 200_000, 2) is the even numbers from 2 to 199,998 (the underscore only makes the number easier to read), and .sample(..., 1000) picks 1,000 different ones. Think of them as prices in pence (100 pence = £1). random.Random(4) uses a seed, 4, so you get the same "random" prices every time. The gift card is 100,001 pence, an odd number. An even number plus an even number is always even, so no pair can ever match. That's the worst case for both functions: the case that makes the most checks. for find in (every_pair, pair_sum) runs the same test with each function in turn, and f"{checks:,}" prints the count with commas.
| Prices | Every pair | Two pointers |
|---|---|---|
| 8 | 28 | 7 |
| 1,000 | 499,500 | 999 |
Both rows are the worst case, with no matching pair. Every pair makes n(n − 1)/2 checks; two pointers make n − 1. On 1,000 prices that's 500 times fewer.
Do two pointers work on an unsorted list?
No. The whole trick depends on the order: "17 is the biggest, so 1 plus anything else is smaller" is only true if the list is sorted. There are two fixes.
One: sort first, with sorted(prices). Python's docs list sorting a list as O(n log n), which grows much more slowly than O(n²). The merge sort post shows where the n log n comes from. Sorting plus two pointers is O(n log n) in all.
Two: skip the sort, and remember the prices you've seen in a set. A set is a collection with no repeats that can tell you very quickly whether something is in it. For each price p, the partner you need is target - p:
def pair_sum_unsorted(prices, target):
seen = set()
for p in prices:
if target - p in seen:
return target - p, p
seen.add(p)
return None
print(pair_sum_unsorted([14, 3, 17, 8, 1, 11, 6, 4], 22))
print(pair_sum_unsorted([14, 3, 17, 8, 1, 11, 6, 4], 16))
(14, 8)
None
When it reaches 8, the partner it needs is 22 − 8 = 14, and 14 is already in seen. Python's docs give x in s for a set as O(1), the same time however big the set is. That's an average, the usual time, not a promise every time: the docs warn that "In the worst case, O(1) operations instead take O(n) time". So this is O(n) on average, with no sort. And because it adds p to seen only after checking, the one 8 can't pair with itself, so £16 gives None. How a set finds things so fast is the topic of the hash maps episode, coming soon.
Where else are two pointers used?
Anywhere two markers step through a list, or through two lists. The most common way is to work in from both ends. Take a palindrome. Wikipedia defines it as "a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards, such as madam or racecar". To check one, compare the two ends, then step both pointers inward:
def is_palindrome(word):
lo, hi = 0, len(word) - 1
while lo < hi:
if word[lo] != word[hi]:
return False
lo += 1
hi -= 1
return True
print(is_palindrome("racecar"), is_palindrome("rocket"))
True False
"racecar" passes after 3 checks: r and r, a and a, c and c. Then both pointers are on the middle e, and the loop stops. "rocket" fails at the first check, because r isn't t. != means "is not equal to".
Reversing a list in place works the same way. "In place" means changing the list itself, without making a new one. Swap the two ends, step inward, repeat:
def reverse_in_place(items):
lo, hi = 0, len(items) - 1
while lo < hi:
items[lo], items[hi] = items[hi], items[lo]
lo += 1
hi -= 1
cards = [1, 2, 3, 4, 5]
reverse_in_place(cards)
print(cards)
[5, 4, 3, 2, 1]
items[lo], items[hi] = items[hi], items[lo] swaps two items in one line. In real code, Python's own cards.reverse() reverses a list for you. The docs describe it as: "Reverse the elements of the list in place."
Databases use the same idea. Remember the slow nested loop join? A faster option is the merge join. The PostgreSQL docs say: "Each relation is sorted on the join attributes before the join starts. Then the two relations are scanned in parallel, and matching rows are combined to form join rows." (An attribute is a column. In parallel means side by side, at the same time.) It's two pointers again, one in each sorted table, stepping forward side by side. The docs add: "This kind of join is attractive because each relation has to be scanned only once." It's the same idea as the merge step in merge sort.
How do you write two pointers in JavaScript?
The same way, with let for the pointers:
function pairSum(prices, target) {
let lo = 0, hi = prices.length - 1;
while (lo < hi) {
const total = prices[lo] + prices[hi];
if (total === target) return [prices[lo], prices[hi]];
if (total < target) lo++;
else hi--;
}
return null;
}
const prices = [1, 3, 4, 6, 8, 11, 14, 17];
console.log(pairSum(prices, 22), pairSum(prices, 16));
[ 8, 14 ] null
=== is JavaScript's strict "is equal to". lo++ adds 1 to lo, and hi-- takes 1 away. JavaScript has no tuples, so the pair comes back as an array (a list), and null is JavaScript's version of Python's None.
Last week's challenge. Episode 8 ended by changing mid = len(items) // 2 to mid = 1 in merge sort, so each split peels off just one item. Our eight numbers still come out sorted, but with 21 comparisons instead of 17.
With a thousand numbers, Python stops with RecursionError: maximum recursion depth exceeded. Each call peels off one item and calls itself on the rest, so about a thousand calls end up waiting, one inside another. (Recursion is a function calling itself.) Python's default limit is 1,000. With splitting in half, they go only 11 calls deep for a thousand numbers. That pile of unfinished calls is called the call stack, and it gets its own episode soon. The merge sort post has the full answer.
1) A museum shop has these prices, in pounds, sorted: 5, 9, 12, 16, 21, 25. Your voucher is worth £28. Trace two pointers. Which pair do you buy, and how many checks does it take?
2) On the eight shop prices with a gift card of £20, which pair do two pointers find, and after how many checks?
3) A check-every-pair loop runs on 8 prices with no matching pair. How many checks does it make? And two pointers, at most?
4) The video's challenge: in pair_sum, change while lo < hi: to while lo <= hi:. What does pair_sum(prices, 16) return now?
Show the answers
1) 12 and 16, in 5 checks. 5 + 25 = 30, too big: hi left. 5 + 21 = 26, too small: lo right. 9 + 21 = 30, too big: hi left. 9 + 16 = 25, too small: lo right. 12 + 16 = 28: found.
2) 3 and 17, in 2 checks. 1 + 17 = 18 is too small, so lo moves right. 3 + 17 = 20: found.
3) 28 checks, because 8 × 7 / 2 = 28. Two pointers make at most 7, which is n − 1.
4) It returns (8, 8), after 8 checks. The pointers close in until both land on the single 8. Then lo <= hi still lets the loop run, and 8 + 8 = 16 counts as a match. That's a wrong answer: the shop has only one £8 item, and no two different prices make £16. So keep lo < hi.
Questions people ask
What is the two pointer technique?
A way to search a list with two indexes instead of one. For a pair sum on a sorted list, one pointer starts at each end. They move toward each other, and each step rules out one item. Other versions start both pointers at the front, or walk through two lists side by side, like the merge in merge sort.
What is the time complexity of two pointers?
O(n) for the pair-sum search: at most n − 1 checks for n items. It uses O(1) extra space, just the two pointers: the extra memory stays the same however long the list is. If the list isn't sorted yet, sorting it first costs O(n log n), so the whole job is O(n log n).
Why can't moving a pointer skip the right pair?
Because each item a pointer moves past has been ruled out. If the sum is too small, the left item plus the biggest item left isn't enough, so the left item plus anything smaller can't be either. If the sum is too big, the right item plus the smallest item left is too much. So the right pair, if there is one, is always still between the pointers.
Why lo < hi and not lo <= hi?
With <=, the loop still runs when both pointers are on the same item, so that item gets added to itself. On our prices with a target of 16 it returns (8, 8), but there's only one 8. lo < hi makes sure the two prices are different items.
Is the two pointer technique faster than binary search for a pair sum?
Yes. You could take each price and use binary search to look for its partner. On 1,000 sorted prices, each binary search takes at most 10 steps, so that's up to 1,000 × 10 = 10,000 steps. Two pointers need at most 999 checks.
What if the same price appears twice?
Two pointers still work. If the list is 4, 8, 8, 13 and the target is 16, the pointers end up on the two different 8s, at different indexes, so pair_sum returns (8, 8). That's correct this time, because there really are two items that cost £8.
Keep going
- Watch the full lesson, Two Pointer Technique in Python: Find a Pair With a Given Sum, Fast, and its Short, Find 2 Numbers That Add to 20: Start at Both Ends. There are also Shorts on finding a pair that sums to 20 in one pass and checking a palindrome with two pointers. More in the letsBug Code series on YouTube. Next in the series: the sliding window (a stretch of a list that slides along it), to find the longest stretch of text without a repeated letter, in one pass.
- The episode before this one: Merge sort in Python, step by step: why it's O(n log n).
- Why counting checks matters: Big O notation in Python. And the same n(n − 1)/2 triangle in bubble sort and insertion sort.
Checked on 29 November 2026 against the 5 sources below.
Sources
- Wikipedia: Birthday problem (23 people, 50.7%, 253 pairs)
- PostgreSQL documentation: Planner/Optimizer (nested loop join and merge join)
- Wikipedia: Palindrome (definition)
- Python documentation: Time complexity of operations on built-in types (set membership O(1) on average, list sort O(n log n))
- Python documentation: Data Structures (
list.reverse()reverses in place)
Every code sample in this post was run in Python 3.13.2 and Node.js 24 before publishing, and every output shown is the real output.