Two Pointers
Move two indices through sorted arrays or strings to find pairs, remove duplicates and partition in linear time.
Beginner · about 6 hours · difficulty 2/5
Learn first: Hashing with Maps and Sets
Two pointers works when moving one index in a known direction can only improve or worsen the answer in a predictable way. It usually needs sorted data or a structure with a clear order.
Variants
- Opposite ends: start at both ends and move inward (Two Sum II on sorted input, Container With Most Water, Valid Palindrome).
- Same direction (slow and fast): a write pointer and a read pointer (Remove Duplicates from Sorted Array, Move Zeroes).
- Fixing one, two-pointer the rest: 3Sum is sort plus a loop plus two pointers, giving O(n^2) instead of O(n^3).
- Two arrays: merge two sorted arrays, intersection of sorted arrays.
Classic problems
Two Sum II, 3Sum, 3Sum Closest, 4Sum, Container With Most Water, Trapping Rain Water (two-pointer version), Remove Duplicates from Sorted Array, Merge Sorted Array, Squares of a Sorted Array.
Pitfalls
- Skipping duplicates wrongly in 3Sum, giving repeated triplets or missing ones.
- Applying two pointers to unsorted data where moving a pointer does not have a clear effect.
- Overflow in 4Sum when adding four large ints.
You are ready to move on when you can explain why, in Container With Most Water, you always move the shorter side.
Key concepts
- Opposite-end pointers
- Slow and fast pointers
- Sort then two pointers
- Skipping duplicates
- Merging two sorted sequences
- Trapping Rain Water
Mini project
Solve these 10 in 7 days, log time and pattern: Two Sum II, Valid Palindrome, Remove Duplicates from Sorted Array, Move Zeroes, Merge Sorted Array, Squares of a Sorted Array, 3Sum, 3Sum Closest, Container With Most Water, Trapping Rain Water.
Check yourself
Why does 3Sum need the array sorted first, and what is its final time complexity?
Free resources
- NeetCode roadmap: Two Pointers (NeetCode)
- USACO Guide: Two Pointers (USACO Guide)
- LeetCode problem set (LeetCode)