programmingconcepts

§ 3.3 · Algorithms

Two pointers

Walk two indexes through an array, usually from both ends toward each other, so one pass replaces a nested loop.

Two pointers is a technique that keeps two indexes into an array and moves them based on what they point at. In a sorted array, for example, start one pointer at each end; if their sum is too small move the left one right, if too big move the right one left. It turns many O(n²) pair searches into O(n).

Time
O(n)
Extra space
O(1)
Needs
Sorted input (for pair sums)
Replaces
An O(n²) nested loop
Requires
ArraysBinary search
def pair_with_sum(a, target):
    """a must be sorted. Returns the indexes of two values that add up to target."""
    left, right = 0, len(a) - 1
    while left < right:
        total = a[left] + a[right]
        if total == target:
            return left, right
        if total < target:
            left += 1
        else:
            right -= 1
    return None

Find two values that add up to 34. The array is sorted, so start with one pointer at each end.

step 0 / 0pointersruled outpair found

Fig. 3.3. Blue cells are under the two pointers, struck-through cells can't be part of the answer, and the pair turns black when found.

Intuition

You have a sorted list of prices and a gift card for exactly 34. Which two items use it up?

The obvious way checks every pair: n(n − 1)/2 sums. But the list is sorted, and that tells you which way to move. Start with the cheapest and the most expensive item. If together they cost too little, the cheapest item can’t work with anything, because the most expensive is already the best partner it has. Drop it and move up. If they cost too much, the most expensive item can’t work with anything either, so drop it and move down.

How it works

  1. Put left at the first index and right at the last.
  2. Add the two values.
  3. If the sum equals the target, you’re done.
  4. If it’s too small, move left one step right, to a bigger value.
  5. If it’s too big, move right one step left, to a smaller value.
  6. Stop when the pointers meet: there’s no pair.

Each step moves one pointer one place inward, so the loop runs at most n − 1 times.

Why it’s correct

When the sum is too small, every pair using a[left] is too small too, since a[right] is the largest value still in play. So a[left] can be crossed out for good, and the figure strikes it through. The same reasoning crosses out a[right] when the sum is too big. Each step rules out a value without ever skipping the answer.

That’s the same trick as binary search: use the sorted order to throw away part of the input after one comparison.

Complexity

Approach Sums checked Extra space
Nested loops, every pair n(n − 1)/2 O(1)
Hash set of values seen n O(n)
Two pointers on sorted input at most n − 1 O(1)

If the input isn’t sorted yet, sorting costs O(n log n), and a hash map may be the better tool.

Where it shows up

  • Pair or triple sums: two sum on sorted input, three sum (fix one value, run two pointers on the rest).
  • Reversing in place: swap a[left] and a[right], move both inward. Also how you check for a palindrome.
  • Merging two sorted arrays: one pointer per array, as in merge sort.
  • Removing duplicates in place: a slow pointer writes, a fast pointer reads.
  • Container with most water: move whichever side is shorter.

Common mistakes

  1. Using it on unsorted input. The “too small, move left” reasoning only holds when the array is sorted.
  2. left <= right instead of left < right. With <=, the loop can pair a value with itself.
  3. Moving both pointers at once. Only the pointer whose value was ruled out should move.

Check yourself

Check yourself

In [1, 4, 6, 9, 12], looking for a sum of 13, the first sum is 1 + 12 = 13. What happens?

Check yourself

In [1, 4, 6, 9, 12], looking for 15, the first sum is 1 + 12 = 13. Which pointer moves?

Sources

  • Steven Halim and Felix Halim, Competitive Programming 3 (2013).
  • Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, exercise 2.3-7 (3rd edition).

Newsletter

One new concept each week, by email.

Signup opens soon.