Two Pointers

Back to Index

Use when: searching pairs/triplets in a sorted array, or partitioning in-place, or detecting cycles.

Signal words: sorted array, pair with target sum, remove duplicates in-place, palindrome, linked list cycle.

Variants

Left / Right (opposite ends)

Start both ends and converge. Common for pair sum problems on sorted arrays.

left, right = 0, len(arr) - 1
while left < right:
    s = arr[left] + arr[right]
    if s == target:
        # found
    elif s < target:
        left += 1
    else:
        right -= 1

Slow / Fast (same direction)

One pointer moves faster. Common for cycle detection, finding middle of linked list, removing nth from end.

slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
# slow is now at the middle

Key Questions to Ask

  • Is the array sorted (or can I sort it)?
  • Am I looking for pairs, or partitioning?
  • Do I need same-direction or opposite-direction pointers?

Problems Using This Pattern