sagelearnai

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

FlavorPointersTypical problems
Opposite endsl = 0, r = n − 1, move inwardpair sum in sorted array, palindrome check, container with most water
Same direction (fast/slow)slow writes, fast readsremove 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 += 1

Why 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.

Problems

  1. Valid Palindrome (Easy): Skip non-alphanumerics, compare from both ends
  2. Valid Palindrome II (Easy): On first mismatch, try skipping either side once
  3. Two Sum II – Sorted Input (Medium): Opposite-end pointers on sorted array
  4. 3Sum (Medium): Sort, fix one, two-pointer the rest, skip duplicates
  5. 3Sum Closest (Medium): Sort + two pointers, track the closest sum
  6. 4Sum (Medium): Sort; two nested fixes + two pointers; skip duplicates
  7. Container With Most Water (Medium): Move the shorter wall inward
  8. Sort Colors (Medium): Dutch national flag: three regions with three pointers
  9. Boats to Save People (Medium): Sort; pair heaviest with lightest when possible
  10. Move Zeroes (Easy): Write pointer compacts non-zeros, then fill zeros
  11. Remove Duplicates from Sorted Array (Easy): Slow pointer keeps the last unique value
  12. Trapping Rain Water (Hard): Water at i = min(maxLeft, maxRight) − h[i]; two pointers
  13. Reverse String (Easy): Swap ends moving inward
  14. Squares of a Sorted Array (Easy): Largest square is at one of the ends; fill from the back
  15. Merge Sorted Array (Easy): Fill nums1 from the back with the larger tail
  16. Reverse Words in a String (Medium): Split on whitespace, reverse, join with single spaces
  17. Rotate Array (Medium): Reverse all, then reverse the two parts
  18. Next Permutation (Medium): Find rightmost ascent, swap with next larger, reverse suffix