Two Pointers — the shape behind dozens of interview problems.
TL;DR
Two cursors moving independently over a sorted or monotone structure. Time O(n) after an optional O(n log n) sort; space O(1).
When to reach for Two Pointers
- Input is sorted or can be sorted.
- Answer involves a pair, triple, or partition with a monotone predicate.
- You want to collapse O(n²) brute force to O(n).
Scenario variants (legal, original)
- Scale Balancer — find a pair summing to target.
- License Plate Mirror — check palindrome under constraints.
- Triple Alloy — find a triplet meeting a condition.
Two Pointers in Python
def pair_sum(nums: list[int], target: int) -> tuple[int, int] | None:
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target:
return (left, right)
if s < target:
left += 1
else:
right -= 1
return NoneSee language-specific tabs at /languages/python/patterns and the SQL variant at /languages/sql/patterns.
Common bugs
- Not sorting when the algorithm requires it.
- Skipping duplicates incorrectly for k-sum variants.
- Advancing the wrong pointer when the sum equals target (infinite loop).
Related patterns
Frequently asked questions
- What is the two pointers pattern?
- Two Pointers is two cursors moving independently over a sorted or monotone structure. Time O(n) after an optional O(n log n) sort; space O(1).
- When should I use two pointers?
- Use it when: Input is sorted or can be sorted. Answer involves a pair, triple, or partition with a monotone predicate. You want to collapse O(n²) brute force to O(n).
- What are the most common two pointers bugs?
- Not sorting when the algorithm requires it. Skipping duplicates incorrectly for k-sum variants. Advancing the wrong pointer when the sum equals target (infinite loop).
- What problems use the two pointers pattern?
- Representative scenarios: Scale Balancer — find a pair summing to target. License Plate Mirror — check palindrome under constraints. Triple Alloy — find a triplet meeting a condition.
- Is two pointers on the Blind 75?
- Yes — Two Pointers is one of the core patterns behind the Blind 75 list. See /blind-75 for the complete mapping.
Run the free diagnostic.
Ten-minute patterns quiz. No card. Personalized loop starts on the other side.