Skip to content

Two Pointers

Two Pointers in under a minute

Two indices move through an array or string, and each step discards part of the search space. That turns an O(n²) “try every pair” loop into O(n), often with O(1) extra memory.

  • The input is sorted, or you are allowed to sort it (and the answer is not indices).
  • You need a pair or triplet that meets a condition (sum, area, equality).
  • You are checking a palindrome or comparing the two ends of a sequence.
  • The brute force is a nested loop and the problem asks for O(1) extra space.
  • Moving one end has a clear effect: it makes the value bigger or smaller, or it can’t possibly help.
left, right = 0, len(items) - 1
while left < right:
value = measure(items[left], items[right])
if value == goal:
record(left, right)
left += 1
right -= 1
elif value < goal: # need more: move the pointer that raises it
left += 1
else: # need less: move the pointer that lowers it
right -= 1

The whole skill is the move rule: say why discarding that pointer’s position can never lose the answer. For triplets, sort, fix one number, and run this loop on the rest.