DSA Master › Topic 2
Two Pointers
Two indices move through the data according to a rule, so you avoid nested loops. On sorted input, comparing the two ends tells you which pointer to move.
Concepts
- Opposite-direction pointers
- Fast/slow pointers
- Sorted-array manipulation
- Dutch National Flag
How to recognise it
- The input is sorted, or sorting it won't break the problem.
- You're looking for a pair or triplet that meets a sum condition.
- You must modify an array in place (remove, partition or compact).
Common pitfalls
- For 3Sum/4Sum, skip duplicate values at every pointer level, not just the outer one.
- Watch for int overflow in 4Sum: compute sums with long.
Problems
- Valid Palindrome (Easy)
- Two Sum II – Input Array Is Sorted (Medium)
- 3Sum (Medium)
- 4Sum (Medium)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Remove Duplicates from Sorted Array (Easy)
- Sort Colors (Medium)
- Move Zeroes (Easy)