Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

The Two-Pointer Technique

Walk in from both ends, or let one pointer chase another.

A sorted array of a million numbers holds about 5×10115\times10^{11} 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 O(n)O(n) time and O(1)O(1) 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 O(n2)O(n^2) 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 XX" checks all n(n−1)/2n(n-1)/2 pairs. On a sorted array, two pointers lo\mathit{lo} and hi\mathit{hi} (the widget's LL and RR) start at both ends. Each step compares one sum with XX and moves the pointer whose value cannot belong to any solution that is left.

python
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)
DerivationProof
  1. 0≤i<j≤n−10\le i<j\le n-1

    Initialization. With lo=0\mathit{lo}=0 and hi=n−1\mathit{hi}=n-1, every pair lies inside the range.

  2. a[lo]+a[j] ≤ a[lo]+a[hi] = s < X,a[\mathit{lo}]+a[j]\ \le\ a[\mathit{lo}]+a[\mathit{hi}]\ =\ s\ <\ X,

    Sum too small. Let s=a[lo]+a[hi]<Xs=a[\mathit{lo}]+a[\mathit{hi}]<X and take a solution (i,j)(i,j) inside the range. If i=loi=\mathit{lo}, then, since j≤hij\le\mathit{hi} and the array is sorted,

  3. a[i]+a[hi] ≥ a[lo]+a[hi] = s > X(i≥lo)a[i]+a[\mathit{hi}]\ \ge\ a[\mathit{lo}]+a[\mathit{hi}]\ =\ s\ >\ X\qquad(i\ge\mathit{lo})

    a contradiction. So i≥lo+1i\ge\mathit{lo}+1 and the solution survives lo←lo+1\mathit{lo}\leftarrow\mathit{lo}+1. Sum too big is the mirror image: if j=hij=\mathit{hi}, then a[i]+a[hi]≥s>Xa[i]+a[\mathit{hi}]\ge s>X, so j≤hi−1j\le\mathit{hi}-1.

  4. #iterations ≤ (n−1)−0 = n−1\#\text{iterations}\ \le\ (n-1)-0\ =\ n-1

    Termination. Every iteration that does not return lowers hi−lo\mathit{hi}-\mathit{lo} by exactly 1, from n−1n-1 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 Θ(n)\Theta(n) time in the worst case and O(1)O(1) extra space. This is a plain worst-case bound: the quantity hi−lo\mathit{hi}-\mathit{lo} falls by one in every iteration. An unsorted input first needs an O(nlog⁡n)O(n\log n) sort. Picture all pairs as a triangle with a row per lo\mathit{lo} and a column per hi\mathit{hi}: each move erases one whole row or column without looking at it.

Check your understanding

You must count the index pairs i<ji<j with a[i]+a[j]=4a[i]+a[j]=4 in a=[1,2,2,2,3]a=[1,2,2,2,3]. A two-pointer loop that adds 1 and moves both pointers inward on every hit returns 2. What is the correct count?

  1. 2
  2. 3
  3. 4
  4. 6
Show the answer

C. 4

1+31+3 gives one pair, and the three 2s give (32)=3\binom{3}{2}=3 more: 4 in all. On a hit, count runs instead of single elements: if a[lo]=a[hi]a[\mathit{lo}]=a[\mathit{hi}], the whole range holds one value with mm copies and contributes m(m−1)/2m(m-1)/2 pairs; otherwise multiply the number of copies of a[lo]a[\mathit{lo}] by the number of copies of a[hi]a[\mathit{hi}], then jump past both runs.

Moving the shorter wall: container with most water

Vertical lines of heights h[0..n−1]h[0..n-1] stand at positions 0,…,n−10,\dots,n-1. Lines i<ji<j and the floor form a container holding min⁡(h[i],h[j])⋅(j−i)\min(h[i],h[j])\cdot(j-i) units of water. Which pair holds the most? The brute force tries all n(n−1)/2n(n-1)/2 pairs.

Two pointers start with the widest container, lo=0\mathit{lo}=0 and hi=n−1\mathit{hi}=n-1, 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.

python
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]))   # 36

n−1n-1 iterations: Θ(n)\Theta(n) time in the worst case, O(1)O(1) extra space.

Check your understanding

The pointers sit on lines with h[lo]=3h[\mathit{lo}]=3 and h[hi]=8h[\mathit{hi}]=8, six positions apart, so the current container holds 3×6=183\times6=18. Why is it safe to discard line lo\mathit{lo}?

  1. Shorter lines are never part of the best container
  2. Every other container that uses line lo\mathit{lo} and a line between the pointers holds at most 3×5=153\times5=15
  3. Line hi\mathit{hi} is the tallest, so it must be in the answer
  4. It is not safe: you must compare h[lo+1]h[\mathit{lo}+1] with h[hi−1]h[\mathit{hi}-1] first
Show the answer

B. Every other container that uses line lo\mathit{lo} and a line between the pointers holds at most 3×5=153\times5=15

Any such container is at most 3 high and at most 5 wide, so it holds at most 15<1815<18. The current container, which uses line lo\mathit{lo}, has already been recorded, so line lo\mathit{lo} has nothing left to offer.

Trapping rain water in O(1) extra space

Bars of heights h[0..n−1]h[0..n-1] stand side by side and it rains. The water above bar ii rises to the lower of the tallest bar on its left and the tallest on its right, both including bar ii:

W(i)=min⁡(ML(i), MR(i))−h[i],ML(i)=max⁡h[0..i],MR(i)=max⁡h[i..n−1].W(i)=\min\big(M_L(i),\,M_R(i)\big)-h[i],\qquad M_L(i)=\max h[0..i],\quad M_R(i)=\max h[i..n-1].

The Prefix Sums & Suffix Sums lesson stores both maxima in two arrays, O(n)O(n) 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.

python
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]))   # 8
DerivationWhy the lower running maximum decides
  1. MR(lo) ≥ max⁡(h[lo], rmax)M_R(\mathit{lo})\ \ge\ \max\big(h[\mathit{lo}],\ \mathit{rmax}\big)

    Invariant. lmax=max⁡h[0..lo−1]\mathit{lmax}=\max h[0..\mathit{lo}-1] and rmax=max⁡h[hi+1..n−1]\mathit{rmax}=\max h[\mathit{hi}+1..n-1] (0 for an empty range), and every bar outside [lo,hi][\mathit{lo},\mathit{hi}] has been counted. Suppose lmax≤rmax\mathit{lmax}\le\mathit{rmax}. The bars right of lo\mathit{lo} include all bars right of hi\mathit{hi}, so

  2. W(lo)=min⁡(h[lo], MR(lo))−h[lo]=0W(\mathit{lo})=\min\big(h[\mathit{lo}],\,M_R(\mathit{lo})\big)-h[\mathit{lo}]=0

    If h[lo]≥lmaxh[\mathit{lo}]\ge\mathit{lmax}, bar lo\mathit{lo} is the tallest from the left so far and holds nothing:

  3. W(lo)=min⁡(lmax, MR(lo))−h[lo]=lmax−h[lo]since lmax≤rmax≤MR(lo)W(\mathit{lo})=\min\big(\mathit{lmax},\,M_R(\mathit{lo})\big)-h[\mathit{lo}]=\mathit{lmax}-h[\mathit{lo}]\quad\text{since}\ \mathit{lmax}\le\mathit{rmax}\le M_R(\mathit{lo})

    If h[lo]<lmaxh[\mathit{lo}]<\mathit{lmax}, the left side is the lower wall:

  4. W(lo)=max⁡(0, lmax−h[lo])W(\mathit{lo})=\max\big(0,\ \mathit{lmax}-h[\mathit{lo}]\big)

    Both cases equal what the code adds, and lmax>rmax\mathit{lmax}>\mathit{rmax} is the mirror image. Each iteration settles one bar, so the loop runs exactly nn times: Θ(n)\Theta(n) time, O(1)O(1) extra space.

Bar settledlmax\mathit{lmax}, rmax\mathit{rmax} beforeSideWater added
0 (height 3)0, 0left0
6 (height 2)3, 0right0
5 (height 1)3, 2right1
4 (height 4)3, 2right0
1 (height 0)3, 4left3
2 (height 2)3, 4left1
3 (height 0)3, 4left3
The run on h=[3,0,2,0,4,1,2]h=[3,0,2,0,4,1,2]: 1+3+1+3=81+3+1+3=8 units, the same total the prefix and suffix maxima give. A third method, a monotonic stack, fills the water layer by layer (see Monotonic Stacks & Queues).

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 rr looks at every element once, and a slow writer ww marks the end of the part you keep. The model problem removes duplicates from a sorted array in place, with no second array.

python
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 a[w−1]a[w-1] instead of a[w]a[w]. With two input sequences, one pointer per sequence gives the merge step of merge sort in O(n+m)O(n+m), and a subsequence test:

python
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 False

Matching s[i]s[i] to its earliest possible occurrence leaves the most room for the rest of ss, so greedy matching never misses a solution. O(∣t∣)O(\abs{t}) time.

3SUM: fix one element, two-pointer the rest

3SUM asks for three elements with sum 0. The brute force tries all (n3)≈n3/6\binom{n}{3}\approx n^3/6 triples. Sort once instead. For each first element a[i]a[i], the other two form a pair-sum problem with target −a[i]-a[i] on the sorted suffix a[i+1..n−1]a[i+1..n-1]. Each of the n−2n-2 scans is linear, so the total is Θ(n2)\Theta(n^2) in the worst case, with O(1)O(1) 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 lo\mathit{lo} past every copy of the middle value: with the first two values fixed, the third is determined.

python
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)]
cpp
#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[i]∣≤109\abs{a[i]}\le10^9, a sum of three can reach 3×109>231−13\times10^9>2^{31}-1, so it is computed in long long.

Think first Delete the line that skips equal first values and run the Python version on [−1,−1,0,1,2][-1,-1,0,1,2]. What goes wrong?

(−1,0,1)(-1,0,1) is reported twice: once with the first −1-1 as a[i]a[i] (the scan finds (−1,−1,2)(-1,-1,2) and then (−1,0,1)(-1,0,1)) and again with the second −1-1 as a[i]a[i]. With the skip, the second −1-1 is passed over, since every triple it starts was already found. A hash set per ii gives another O(n2)O(n^2) algorithm, expected rather than worst case. Whether 3SUM can be solved in O(n2−ε)O(n^{2-\varepsilon}) 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 XX", "closest to XX", "count the pairs with sum at most TT", "triples with sum 0".
  • "In place" or "O(1)O(1) 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 nn up to 10510^5 or 10610^6, where n2/2n^2/2 pairs are far too many.
Problem (in brief)Key ideaCost
Pair with sum XX in a sorted arrayToo big: drop the right end; too small: drop the leftO(n)O(n)
Container with most waterRecord the area, then move the shorter lineO(n)O(n)
Trapping rain waterSettle the side whose running maximum is lowerO(n)O(n) time, O(1)O(1) space
All distinct triples with sum 0 (3SUM)Sort, fix the first, pair-sum the rest, skip duplicatesO(n2)O(n^2)
Squares of a sorted array, in sorted orderThe largest square is at one of the two ends: fill the output from the backO(n)O(n)
Five classic problems; the read/write pattern adds in-place dedupe and filtering, merging and subsequence tests.
Check your understanding

Which of these problems does not yield to a scan with pointers at both ends?

  1. Is a string a palindrome?
  2. The squares of a sorted array, in sorted order
  3. The longest subarray with sum exactly kk, where values may be negative
  4. The pair in a sorted array whose sum is closest to XX
Show the answer

C. The longest subarray with sum exactly kk, 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 O(n)O(n) 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 n−1n-1 steps, Θ(n)\Theta(n) worst case, plus O(nlog⁡n)O(n\log n) 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 O(n)O(n).
  • 3SUM is sorting plus one pair-sum scan per first element, skipping duplicates: Θ(n2)\Theta(n^2) 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.

Question 1

In pair sum on a sorted array, a[lo]+a[hi]<Xa[\mathit{lo}]+a[\mathit{hi}]<X. What justifies discarding a[lo]a[\mathit{lo}] for good?

  1. a[lo]a[\mathit{lo}] is the smallest element of the whole array
  2. hi\mathit{hi} moves next anyway, so nothing is lost
  3. For every remaining partner j≤hij\le\mathit{hi}, a[lo]+a[j]≤a[lo]+a[hi]<Xa[\mathit{lo}]+a[j]\le a[\mathit{lo}]+a[\mathit{hi}]<X
  4. The target must exceed 2 a[lo]2\,a[\mathit{lo}]
Show the answer

C. For every remaining partner j≤hij\le\mathit{hi}, a[lo]+a[j]≤a[lo]+a[hi]<Xa[\mathit{lo}]+a[j]\le a[\mathit{lo}]+a[\mathit{hi}]<X

a[hi]a[\mathit{hi}] is the largest partner still available, and even it falls short, so no remaining pair uses a[lo]a[\mathit{lo}]. That is the invariant's "sum too small" case.

Question 2

In container with most water, h[lo]=h[hi]=5h[\mathit{lo}]=h[\mathit{hi}]=5. Which pointer may move?

  1. Only lo\mathit{lo}
  2. Only hi\mathit{hi}
  3. Neither, until you compare h[lo+1]h[\mathit{lo}+1] with h[hi−1]h[\mathit{hi}-1]
  4. 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 5(hi−lo)5(\mathit{hi}-\mathit{lo}).

Question 3

You call dedupe_sorted on the list [1,1,2,3,3,3,4][1,1,2,3,3,3,4]. What does the list hold afterward, and what does the call return?

  1. [1,2,3,4][1,2,3,4], returning 4
  2. [1,2,3,4,0,0,0][1,2,3,4,0,0,0], returning 4
  3. [1,2,3,4,3,3,4][1,2,3,4,3,3,4], returning 4
  4. [1,2,3,4,3,3,4][1,2,3,4,3,3,4], returning 7
Show the answer

C. [1,2,3,4,3,3,4][1,2,3,4,3,3,4], returning 4

The writer copies 2, 3 and 4 into positions 1, 2 and 3; nothing is deleted or cleared. The first w+1=4w+1=4 cells are the answer, and the rest is leftover input that the caller ignores (or truncates, as del a[k:] would).

Question 4

Count the pairs i<ji<j with a[i]+a[j]≤Ta[i]+a[j]\le T in an unsorted array of n=105n=10^5 integers. Which method fits?

  1. Sort, then for each lo\mathit{lo} move hi\mathit{hi} down while a[lo]+a[hi]>Ta[\mathit{lo}]+a[\mathit{hi}]>T and add hi−lo\mathit{hi}-\mathit{lo}
  2. A hash set of complements T−a[i]T-a[i]
  3. A sliding window over the array in its original order
  4. Prefix sums of the array
Show the answer

A. Sort, then for each lo\mathit{lo} move hi\mathit{hi} down while a[lo]+a[hi]>Ta[\mathit{lo}]+a[\mathit{hi}]>T and add hi−lo\mathit{hi}-\mathit{lo}

Pairs do not care about order, so sorting is allowed. Once a[lo]+a[hi]≤Ta[\mathit{lo}]+a[\mathit{hi}]\le T, every partner between them also works, giving hi−lo\mathit{hi}-\mathit{lo} pairs at once, and hi\mathit{hi} only ever moves down. O(nlog⁡n)O(n\log n) in all, against 5×1095\times10^9 pairs for the brute force.

Go deeper

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.