A quick reference for two pointer techniques and problems to practice.| Pattern | When to Use | Time |
|---|
| Opposite Ends | Sorted array + find pair, palindrome check | O(n) |
| Same Direction | In-place modifications, merging arrays | O(n) |
| Fast & Slow | Cycle detection, find middle of list | O(n) |
- Basics - Core concepts, when to use each pattern
- Opposite Ends - Two Sum, 3Sum, Container With Water
- Same Direction - Remove duplicates, move elements, merge arrays
- Fast & Slow - Cycle detection, find middle, Floyd's algorithm
| If you see... | Use... |
|---|
| Sorted array + find pair with sum | Opposite ends |
| Check if palindrome | Opposite ends |
| Remove/modify elements in-place | Same direction |
| Merge two sorted arrays | Same direction |
| Linked list cycle | Fast & slow |
| Find middle of linked list | Fast & slow |
| Reduce O(n²) to O(n) | Usually opposite ends |
- Off-by-one errors: Be careful with loop conditions (
left < right vs left <= right). - Forgetting to check fast.next: In fast/slow, always verify
fast and fast.next exist before moving. - Wrong pointer to move: In opposite ends, think carefully about which pointer movement can improve the result.
- Skipping duplicates incorrectly: In 3Sum-type problems, skip duplicates after finding a valid solution, not before.
- Two pointers is about eliminating redundant comparisons by using the structure of the problem.
- All three patterns achieve O(n) time and O(1) space.
- The key decision is always which pointer to move and why.
- Two pointers often appears as a subroutine in larger problems (e.g., 3Sum uses 2Sum).