Pattern 01
Two Pointers
Compare or converge values from both ends of an array.
When to use
Use when you are comparing values from two sides, moving inward, or scanning a sorted array with left/right indices. Classic signals: palindrome check, pair sum, removing duplicates.
Core intuition
Instead of checking every pair with nested loops O(n²), move two pointers intelligently based on the current state. Each step eliminates a chunk of work.
Template
def two_pointers(arr):
left, right = 0, len(arr) - 1
while left < right:
current = arr[left] + arr[right]
if current == target:
return [left, right]
elif current < target:
left += 1
else:
right -= 1
return []Suggested problems
Key takeaways
- ›Usually a sorted array or a mirrored comparison
- ›Start one pointer on the left, one on the right
- ›If current state is too small → move left pointer right
- ›If current state is too big → move right pointer left
- ›If chars/values should match → compare both and move inward
You'll see this when...
- ›Sorted array + find pair that sums to target
- ›Check if string is a palindrome
- ›Remove duplicates in-place
- ›Trap water between bars
- ›Find two numbers that satisfy a condition