Topic Lesson
Learn Two Pointers from scratch
A complete 4-step path: handwritten notebook primer, animated visualizer, speed check quiz, and compiler practice.
What is Two Pointers
notebook noteTwo pointers is a search coordinated by two fingers placed on different entries of an ordered row, stepping inward toward each other or advancing at different speeds. Instead of scanning with nested loops that re-examine identical pairs, each pointer moves unidirectionally based on comparisons. Because every movement permanently prunes bad candidate combinations, the search inspects the collection in a single joint pass.
When to reach for it
Reach for two pointers when problems require finding index pairs, reversing sequences, trapping rainwater, or filtering duplicates in sorted arrays. When an input is already sorted and an exhaustive search takes quadratic time, opposing pointers meeting in the center often solve it linearly. Fast and slow pointer variations also detect cycles or locate midpoint nodes across linked sequences.
How to think about it
Initialize pointers at opposing edges for convergent searches, or start both at the beginning to move at different speeds. Under a convergent setup, calculate current pair metrics; if the sum falls short of your target, advance the lower pointer rightward to increase value, and if it exceeds your target, shift the upper pointer leftward to decrease value. Each pointer move throws away only pairs that were already known to be wrong, so the right answer is never missed.
Operation costs
measured big-O| Operation | Time |
|---|---|
| converging scan across sorted collection | O(n) |
| slow and fast cycle traversal | O(n) |
| auxiliary memory overhead for pointer markers | O(1) |
Common mistakes to avoid
- Applying convergent opposite-end pointers to an unsorted collection without realizing that sorting was a necessary precondition for direction-based pruning.
- Allowing pointers to cross past one another or crash into identical indices when matching duplicate values, skipping the termination condition.
- Forgetting to advance pointers past repeated values during duplicate-skipping loops, creating unexpected infinite iterations on matching elements.