Two pointers

In one sentence

Move two indexes through a sorted array, string or linked list so every step discards candidates for good: O(n) time, O(1) space, where brute force checks all O(n²) pairs.

Analogy: Picking two gifts that cost exactly $50 from a price-sorted shelf: start with the cheapest and the priciest. Over budget, put the pricey one back; under, trade the cheap one up.

On sorted input each comparison proves one pointer's value can't be in any answer, so that pointer moves and never comes back.

How it works

  • Opposite ends on sorted input: sum too small, move lo right; too big, move hi left.
  • Fast/slow on linked lists: they meet if there is a cycle; slow lands on the middle.
  • Read/write pointers partition or dedupe in place with O(1) extra space.
  • Before coding, say why each move is safe: that argument is the correctness proof.
  • Unsorted input costs O(n log n) to sort first; a hash map keeps the original indexes.

Check yourself

Answer to mark it learned; your answers aren't scored.

Sorted array: find a pair summing to the target with O(1) extra space. At the current lo and hi, the sum is less than the target. Which move is justified?

Go deeper

Loops in motion Interactive labSliding window, step by step Interactive lab
Solve it in Python 10
Full explanation

Two indexes walk the data, and every move rules out candidates you never revisit, so the total work is O(n).

Three shapes:

  • Opposite ends (sorted input): lo at the start, hi at the end. If a[lo] + a[hi] is too small, only lo += 1 can help; too big, hi -= 1. Pair sums, palindromes, container with most water, and 3Sum (fix one element, two-pointer the rest: O(n²)).
  • Fast/slow on a linked list: fast moves two steps, slow one. They meet if there is a cycle (Floyd), and slow sits at the middle when fast reaches the end.
  • Read/write: read scans everything, write marks where the next kept element goes. Dedupe a sorted array or move zeros in place; a third pointer gives the Dutch national flag partition.

The correctness proof is the argument for why a move is safe: say it out loud. Unsorted input costs O(n log n) to sort first; if you must return original indexes, Hash maps, sets and prefix sums are simpler.

Code Opposite ends, fast/slow and read/write templates
pythonOpposite ends, fast/slow and read/write templates
def pair_with_sum(a: list[int], target: int) -> tuple[int, int] | None:
    lo, hi = 0, len(a) - 1               # a must be sorted
    while lo < hi:                       # < not <=: an element can't pair with itself
        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
        else:
            hi -= 1                      # a[hi] is too big even with the smallest partner
    return None

def has_cycle(head) -> bool:
    slow = fast = head
    while fast and fast.next:            # fast jumps two nodes: both must exist
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False

def dedupe_sorted(a: list[int]) -> int:
    write = 0
    for read in range(len(a)):
        if read == 0 or a[read] != a[read - 1]:
            a[write] = a[read]
            write += 1
    return write                         # a[:write] holds the unique values
Real example

3Sum (all unique triplets summing to 0): sort, then for each i run opposite-ends pointers on a[i+1:] looking for −a[i]. That is O(n log n) + O(n²) versus O(n³) brute force: for n = 3,000, ~4.5×10⁶ pointer moves (n²/2) instead of ~4.5×10⁹ triplets (n³/6). Skip equal neighbors for i, lo and hi so each triplet appears once.

Trade-offs +3 · −2

+ You gain

  • O(1) extra space, usually in place.
  • Linear scans: cache-friendly and easy to argue with an invariant.
  • Extends to 3Sum and kSum by fixing the outer elements.

− You pay

  • Opposite ends needs sorted input; sorting costs O(n log n) and loses original indexes.
  • Off-by-one and duplicate-skipping bugs are easy to write.

Use it when

Sorted arrays or strings, pair and triplet sums, palindromes, merging two sorted lists, in-place partitioning, and linked-list cycle or middle detection.

Avoid it when

Unsorted input when you must return original indexes (use a hash map), or when no move provably discards candidates: then it is a guess, not an algorithm.

Numbers to know 4
  • Pair sum on sorted input: O(n) time, O(1) space; O(n log n) if you sort first.
  • 3Sum: O(n²) with sort plus two pointers, versus O(n³) brute force.
  • Floyd cycle detection: O(n) time and O(1) space, versus O(n) space for a visited set.
  • Merging two sorted arrays: O(n + m) with one pointer each.
Common pitfalls 4
  • lo <= hi in pair sums: an element pairs with itself.
  • Fast/slow without checking fast.next: a null dereference when fast lands on the last node (odd-length lists).
  • Not skipping duplicates in 3Sum: the same triplet appears several times.
  • Sorting when the answer needs original indexes: you return positions in the sorted copy.
Interview questions 2

Answer out loud first, then reveal.

How do you know two pointers will work?Show answer

I look for sorted input, or input I can afford to sort, and a question about pairs, ranges or palindromes. Then I check the key property: at each step, can I prove one pointer's element can't be in any answer? For pair sums, if a[lo] + a[hi] is too small, a[lo] fails even with the largest partner, so lo moves. If I can't state that argument, I don't use it.

Find where a linked-list cycle starts, in O(1) space.Show answer

Floyd's algorithm. Slow moves one step and fast two; if they meet, there's a cycle. Then I put one pointer back at the head and move both one step at a time: they meet at the cycle's entrance, because the head-to-entrance distance matches the meeting-point-to-entrance distance modulo the cycle length. O(n) time and O(1) space, versus O(n) space for a visited set.