Two Pointers
Signal: a sorted array (or one you can sort), pairs or triplets meeting a condition, palindromes, partitioning in place, or "compare from both ends".
Core idea: keep two indices and move one of them based on a comparison. Each move provably eliminates candidates, so you scan in O(n) instead of checking O(n²) pairs.
Two flavors
| Flavor | Pointers | Typical problems |
|---|---|---|
| Opposite ends | l = 0, r = n − 1, move inward | pair sum in sorted array, palindrome check, container with most water |
| Same direction (fast/slow) | slow writes, fast reads | remove duplicates in place, move zeroes, partitioning |
python
# Opposite ends on a sorted array
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target: return l, r
if s < target: l += 1 # need bigger: drop the smallest
else: r -= 1 # need smaller: drop the largest
# Same direction: compact non-zero values to the front
w = 0
for x in a:
if x != 0:
a[w] = x; w += 1Why moving a pointer is safe
In the sorted pair-sum: if a[l] + a[r] < target, then a[l] paired with anything in (l, r] is at most a[l] + a[r] < target, so a[l] can never be part of an answer. Discard it with l += 1. Making this "elimination argument" explicit is what interviewers want to hear.