Two Pointers
When to use: sorted arrays, pairs/triplets with a target sum, palindromes, in-place partitioning.
- Opposite ends (
l=0, r=n-1): move the side that can only improve the answer (sorted sum search, container area, palindrome check). - Same direction (slow/fast): slow marks the "kept" prefix, fast scans (remove/move elements in place).
- Sorting first often turns an O(n²) search into O(n log n).
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
else: r -= 1 # need smaller
Problems
Showing 22 of 22