← Lessons

quiz vs the machine

Silver1080

Algorithms

The Two Pointers Pattern

Walk two indices through a sorted sequence to find pairs without nested loops.

4 min read · intro · beat Silver to climb

Two indices instead of two loops

When data is sorted, you often do not need a nested loop to find a pair that meets some condition. The two pointers pattern places one index at the start and another at the end, then moves them toward each other based on what the current pair tells you.

The convergent walk

For a classic pair sum problem you compare the sum of the values at both pointers against a target.

  • If the sum is too small, move the left pointer right to pick a larger value.
  • If the sum is too large, move the right pointer left to pick a smaller value.
  • If the sum matches, you have found the pair.

Because each step discards one end of the search space, the pointers meet after one linear pass instead of checking every pair.

Beyond pair sums

The same idea drives many tasks: removing duplicates in place, reversing an array, partitioning around a pivot, and merging two sorted lists. A same direction variant uses a slow and a fast pointer over one array to compact or filter elements.

Key idea

On sorted data, two converging pointers replace a nested loop because each comparison lets you discard one whole end of the remaining search range.

Check yourself

Answer to earn rating on the learn ladder.

1. What precondition makes the converging two pointers technique valid for pair sums?

2. If the current pair sum exceeds the target, which move helps?