The Two-Pointer Technique
Walk in from both ends, or let one pointer chase another.
A sorted array of a million numbers holds about pairs, yet the pair with a given sum turns up after at most 999,999 comparisons. The reason is a one-line argument: when a sum is too big, the larger number has no partner left, so it can be thrown away for good. The same argument, in different clothes, solves container with most water, trapping rain water and 3SUM.
What you’ll learn
- Implement opposite-end pointers for pair sum on a sorted array, and prove with an invariant that the walk never discards the answer.
- Solve container with most water and trapping rain water in time and extra space, and justify which pointer moves.
- Edit arrays in place with same-direction read and write pointers, merge sorted sequences, and test subsequences.
- Extend pair sum to 3SUM in time, skipping duplicates correctly.
- Recognize two-pointer problems, reject the look-alikes, and avoid the classic bugs with duplicates, loops and overflow.
Opposite ends: pair sum, with a proof
The brute force for "two elements with sum " checks all pairs. On a sorted array, two pointers and (the widget's and ) start at both ends. Each step compares one sum with and moves the pointer whose value cannot belong to any solution that is left.
def pair_sum_sorted(a, target):
"""Indices i < j with a[i] + a[j] == target, or None. a must be sorted."""
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
if s == target:
return lo, hi
if s < target:
lo += 1 # a[lo] is too small even with the largest partner left
else:
hi -= 1 # a[hi] is too big even with the smallest partner left
return None
print(pair_sum_sorted([-21, -14, -9, -5, -2, 3, 6, 11, 16, 24], 4)) # (4, 6)Initialization. With and , every pair lies inside the range.
Sum too small. Let and take a solution inside the range. If , then, since and the array is sorted,
a contradiction. So and the solution survives . Sum too big is the mirror image: if , then , so .
Termination. Every iteration that does not return lowers by exactly 1, from down to at least 0. If the loop ends without a hit, the range holds no pair, so by the invariant no solution exists.
So the scan takes time in the worst case and extra space. This is a plain worst-case bound: the quantity falls by one in every iteration. An unsorted input first needs an sort. Picture all pairs as a triangle with a row per and a column per : each move erases one whole row or column without looking at it.
You must count the index pairs with in . A two-pointer loop that adds 1 and moves both pointers inward on every hit returns 2. What is the correct count?
- 2
- 3
- 4
- 6
Show the answer
C. 4
gives one pair, and the three 2s give more: 4 in all. On a hit, count runs instead of single elements: if , the whole range holds one value with copies and contributes pairs; otherwise multiply the number of copies of by the number of copies of , then jump past both runs.
Moving the shorter wall: container with most water
Vertical lines of heights stand at positions . Lines and the floor form a container holding units of water. Which pair holds the most? The brute force tries all pairs.
Two pointers start with the widest container, and , record its area, and move the shorter line inward. That looks like a gamble, since moving inward always loses width, but it is a proof.
def max_area(h):
lo, hi, best = 0, len(h) - 1, 0
while lo < hi:
best = max(best, min(h[lo], h[hi]) * (hi - lo))
if h[lo] < h[hi]:
lo += 1 # line lo has no better partner left
else:
hi -= 1 # line hi has none (on a tie, either is safe)
return best
print(max_area([3, 4, 6, 1, 2, 8, 9, 6, 7, 5])) # 36iterations: time in the worst case, extra space.
The pointers sit on lines with and , six positions apart, so the current container holds . Why is it safe to discard line ?
- Shorter lines are never part of the best container
- Every other container that uses line and a line between the pointers holds at most
- Line is the tallest, so it must be in the answer
- It is not safe: you must compare with first
Show the answer
B. Every other container that uses line and a line between the pointers holds at most
Any such container is at most 3 high and at most 5 wide, so it holds at most . The current container, which uses line , has already been recorded, so line has nothing left to offer.
Trapping rain water in O(1) extra space
Bars of heights stand side by side and it rains. The water above bar rises to the lower of the tallest bar on its left and the tallest on its right, both including bar :
The Prefix Sums & Suffix Sums lesson stores both maxima in two arrays, extra space. Two pointers need only four numbers: work inward from both ends, always on the side whose running maximum is lower, because that side alone decides the water level there.
def trap(h):
lo, hi = 0, len(h) - 1
lmax = rmax = water = 0 # lmax = max(h[:lo]), rmax = max(h[hi+1:])
while lo <= hi:
if lmax <= rmax: # bar lo is limited by its left side
water += max(0, lmax - h[lo])
lmax = max(lmax, h[lo])
lo += 1
else: # bar hi is limited by its right side
water += max(0, rmax - h[hi])
rmax = max(rmax, h[hi])
hi -= 1
return water
print(trap([3, 0, 2, 0, 4, 1, 2])) # 8Invariant. and (0 for an empty range), and every bar outside has been counted. Suppose . The bars right of include all bars right of , so
If , bar is the tallest from the left so far and holds nothing:
If , the left side is the lower wall:
Both cases equal what the code adds, and is the mirror image. Each iteration settles one bar, so the loop runs exactly times: time, extra space.
| Bar settled | , before | Side | Water added |
|---|---|---|---|
| 0 (height 3) | 0, 0 | left | 0 |
| 6 (height 2) | 3, 0 | right | 0 |
| 5 (height 1) | 3, 2 | right | 1 |
| 4 (height 4) | 3, 2 | right | 0 |
| 1 (height 0) | 3, 4 | left | 3 |
| 2 (height 2) | 3, 4 | left | 1 |
| 3 (height 0) | 3, 4 | left | 3 |
Same direction: a reader and a writer
Not every two-pointer loop squeezes from both ends. In the read/write pattern both pointers move right: a fast reader looks at every element once, and a slow writer marks the end of the part you keep. The model problem removes duplicates from a sorted array in place, with no second array.
def dedupe_sorted(a):
"""Keep one copy of each value of the sorted list a, in place; return the new length."""
if not a:
return 0
w = 0 # a[0..w] = the distinct values read so far
for r in range(1, len(a)): # r reads every element once
if a[r] != a[w]:
w += 1
a[w] = a[r]
return w + 1
a = [2, 2, 3, 5, 5, 5, 6, 8, 8, 9, 11, 11]
k = dedupe_sorted(a)
print(k, a[:k]) # 7 [2, 3, 5, 6, 8, 9, 11]The same skeleton handles a family of in-place edits: keep the elements that pass a test (remove every copy of a value, move zeros to the end in order), or keep at most two copies of each value by comparing with instead of . With two input sequences, one pointer per sequence gives the merge step of merge sort in , and a subsequence test:
def is_subsequence(s, t):
"""Can s be obtained from t by deleting characters?"""
i = 0
for c in t: # one pass over t
if i < len(s) and s[i] == c:
i += 1 # match greedily: the earliest copy is never worse
return i == len(s)
print(is_subsequence("ace", "abcde"), is_subsequence("aec", "abcde")) # True FalseMatching to its earliest possible occurrence leaves the most room for the rest of , so greedy matching never misses a solution. time.
3SUM: fix one element, two-pointer the rest
3SUM asks for three elements with sum 0. The brute force tries all triples. Sort once instead. For each first element , the other two form a pair-sum problem with target on the sorted suffix . Each of the scans is linear, so the total is in the worst case, with extra space beyond the sort and the output.
Most versions want distinct value triples. Two rules handle repeats. Skip a first value equal to the previous one, since it would produce the same triples. After a hit, move past every copy of the middle value: with the first two values fixed, the third is determined.
def three_sum(a):
"""All distinct value triples (x, y, z), x <= y <= z, from a with x + y + z == 0."""
a = sorted(a)
n, out = len(a), []
for i in range(n - 2):
if i > 0 and a[i] == a[i - 1]:
continue # same first value: same triples again
lo, hi = i + 1, n - 1
while lo < hi:
s = a[i] + a[lo] + a[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
out.append((a[i], a[lo], a[hi]))
lo += 1
hi -= 1
while lo < hi and a[lo] == a[lo - 1]:
lo += 1 # skip copies of the middle value
return out
print(three_sum([-1, 0, 1, 2, -1, -4])) # [(-1, -1, 2), (-1, 0, 1)]#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n;
if (scanf("%d", &n) != 1) return 0;
vector<long long> a(n);
for (auto &x : a) scanf("%lld", &x);
sort(a.begin(), a.end());
long long triples = 0; // distinct value triples with sum 0
for (int i = 0; i + 2 < n; i++) {
if (i > 0 && a[i] == a[i - 1]) continue; // same first value as before
int lo = i + 1, hi = n - 1;
while (lo < hi) {
long long s = a[i] + a[lo] + a[hi]; // 3e9 does not fit in a 32-bit int
if (s < 0) lo++;
else if (s > 0) hi--;
else {
triples++;
lo++, hi--;
while (lo < hi && a[lo] == a[lo - 1]) lo++;
}
}
}
printf("%lld\n", triples);
}The contest version counts distinct triples. With , a sum of three can reach , so it is computed in long long.
Think first Delete the line that skips equal first values and run the Python version on . What goes wrong?
is reported twice: once with the first as (the scan finds and then ) and again with the second as . With the skip, the second is passed over, since every triple it starts was already found. A hash set per gives another algorithm, expected rather than worst case. Whether 3SUM can be solved in time at all is open: see 3SUM & the k-SUM Problem.
Recognizing it
Reach for two pointers when you see these signals:
- Sorted input, or an order you may destroy. Pairs and triples do not care about positions, so you may sort first.
- A target or bound on two (or three) elements: "pair with sum ", "closest to ", "count the pairs with sum at most ", "triples with sum 0".
- "In place" or " extra space" for filtering, compacting or merging a sequence.
- Two ends that interact: palindromes, containers, the largest square of a sorted array that has negatives.
- Constraints with up to or , where pairs are far too many.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Pair with sum in a sorted array | Too big: drop the right end; too small: drop the left | |
| Container with most water | Record the area, then move the shorter line | |
| Trapping rain water | Settle the side whose running maximum is lower | time, space |
| All distinct triples with sum 0 (3SUM) | Sort, fix the first, pair-sum the rest, skip duplicates | |
| Squares of a sorted array, in sorted order | The largest square is at one of the two ends: fill the output from the back |
Which of these problems does not yield to a scan with pointers at both ends?
- Is a string a palindrome?
- The squares of a sorted array, in sorted order
- The longest subarray with sum exactly , where values may be negative
- The pair in a sorted array whose sum is closest to
Show the answer
C. The longest subarray with sum exactly , where values may be negative
Subarrays must keep the original order, so you cannot sort, and with negative values neither end's move has a predictable effect on the sum. Prefix sums with a hash map of first occurrences solve it in expected time.
Key takeaways
- Opposite-end pointers on sorted data: each comparison rules out a whole row or column of pairs, so the scan takes at most steps, worst case, plus if you must sort first.
- Correctness is an invariant: if a solution exists, one stays between the pointers. Container with most water and trapping rain water use the same "the discarded side cannot do better" argument.
- Same-direction pointers read every element once and write the kept ones behind the reader: in-place dedupe and filtering, merging and subsequence tests, all in .
- 3SUM is sorting plus one pair-sum scan per first element, skipping duplicates: worst case.
- Recognize it by sorted (or sortable) data with pairs or triples, or by in-place edits; send unsorted-with-positions problems to a hash map and subarray sums with negatives to prefix sums.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In pair sum on a sorted array, . What justifies discarding for good?
- is the smallest element of the whole array
- moves next anyway, so nothing is lost
- For every remaining partner ,
- The target must exceed
Show the answer
C. For every remaining partner ,
is the largest partner still available, and even it falls short, so no remaining pair uses . That is the invariant's "sum too small" case.
In container with most water, . Which pointer may move?
- Only
- Only
- Neither, until you compare with
- Either one: every container that uses one of these lines and a line in between holds less than the current one
Show the answer
D. Either one: every container that uses one of these lines and a line in between holds less than the current one
The proof needs only that the discarded line is not taller than the other. With a tie, both lines qualify: any container using one of them and an inner line is at most 5 high and narrower, so it holds less than .
You call dedupe_sorted on the list . What does the list hold afterward, and what does the call return?
- , returning 4
- , returning 4
- , returning 4
- , returning 7
Show the answer
C. , returning 4
The writer copies 2, 3 and 4 into positions 1, 2 and 3; nothing is deleted or cleared. The first cells are the answer, and the rest is leftover input that the caller ignores (or truncates, as del a[k:] would).
Count the pairs with in an unsorted array of integers. Which method fits?
- Sort, then for each move down while and add
- A hash set of complements
- A sliding window over the array in its original order
- Prefix sums of the array
Show the answer
A. Sort, then for each move down while and add
Pairs do not care about order, so sorting is allowed. Once , every partner between them also works, giving pairs at once, and only ever moves down. in all, against pairs for the brute force.
Go deeper
- 3SUM & the k-SUM Problem · From quadratic 3SUM with two pointers to the 3SUM conjecture.
- In-Place Partitioning · Dutch national flag, Lomuto and Hoare, and the invariants that make them correct.
- Why Two Pointers Work · Monotonicity, the sorted-matrix picture and proofs that no pair is missed.
Further reading
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), §8.1 "Two pointers method".
- S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020).
- D. Gries, The Science of Programming (Springer, 1981): developing loops from their invariants.