Two Pointers
Move two indices through a sequence, from both ends or at different speeds, to solve pair-sum, partition and in-place problems in linear time.
Beginner · about 5 hours · difficulty 2/5
Learn first: Array and String Fundamentals
The two-pointer technique uses two indices that move through the data in a coordinated way. Because each pointer moves at most n steps, the total work is O(n) even though it can look like a nested loop.
Three flavours
- Opposite ends on a sorted array: start
l = 0,r = n - 1. If the sum is too small move l right, if too large move r left. Solves pair sum, 3Sum (fix one element, two-pointer the rest), Container With Most Water and palindrome checks. - Same direction (read/write): a slow pointer marks where to write, a fast pointer scans. Solves Remove Duplicates, Move Zeroes and partitioning in place.
- Two sequences: one pointer per array, as in merging two sorted arrays or checking if one string is a subsequence of another.
Why it works
On a sorted array, moving the pointer that cannot possibly be part of a better answer safely discards candidates. Being able to state this argument ("if the sum is too big, no pair using r can work with any larger l") is what interviewers look for.
Pitfalls
- Forgetting to sort first, or sorting when original indices are needed (then use a hash map instead).
- Duplicate handling in 3Sum: skip equal neighbours after recording a triple.
- Infinite loops when neither pointer moves in some branch.
Fast and slow pointers on linked lists are a cousin of this pattern and appear in the linked list topic.
Key concepts
- Opposite-end pointers on sorted data
- Read/write pointers for in-place edits
- Merging two sorted sequences
- 3Sum and k-sum reduction
- Duplicate skipping
- Correctness argument: Why discarding is safe
Mini project
Solve 8 problems: Two Sum II, 3Sum, Container With Most Water, Remove Duplicates from Sorted Array, Merge Sorted Array, Valid Palindrome II, Is Subsequence, and Trapping Rain Water (two-pointer version).
Check yourself
In Container With Most Water, why is it always safe to move the pointer at the shorter line inward?
Free resources
- NeetCode Roadmap (Two Pointers) (NeetCode)
- Two pointers technique (GeeksforGeeks)
- LeetCode Problem Set (LeetCode)