Learn how two indices can reduce repeated work and turn many array and string problems into clean O(n) solutions.
Two pointers means maintaining two positions and moving them according to a proven rule.
One pointer can start left and another right, or both can move forward.
Instead of checking every pair, pointer movement can eliminate large parts of the search space.
Sorted order, boundaries or a monotonic condition usually tells you which pointer can move safely.
The important part is not having two variables. It is knowing why a pointer can move without losing the answer.
Example: find two values whose sum equals a target in a sorted array.
If left + right is too small → move LEFT. If too large → move RIGHT.
Left starts at 0 and right at n−1. Common for sorted two-sum and palindrome problems.
Both pointers move forward. Common for filtering, partitioning and removing duplicates.
One pointer moves faster. Common in linked lists for cycles and middle-node problems.
Pointer movement must reduce the search space while preserving correctness.
| Signal | Technique | Example |
|---|---|---|
| Sorted array + target pair | Opposite pointers | Two Sum II |
| Check from both ends | Opposite pointers | Valid Palindrome |
| Remove duplicates in-place | Same-direction | Remove Duplicates |
| Move elements by condition | Two pointers | Move Zeroes |
| Linked-list cycle | Fast + slow | Floyd Cycle Detection |