The pattern: two pointers
Walk an array or string with two indexes at once, from both ends or side by side, to replace nested loops with a single pass.
Many problems that look like "check every pair" (O(n²)) can be solved by moving two indexes through the data in a single pass (O(n)). Each step uses what you just learned to throw away a choice that can't be the answer.
01The three shapes
1. From both ends, moving inward. Compare or combine the two ends, then move one or both inward.
l = 0 ; r = n - 1
while l < r:
look at a[l] and a[r]
move l right, r left, or bothUsed for: palindromes, pairs in a sorted array (Two Sum II, 3Sum, 4Sum), Container With Most Water.
2. Two sequences side by side. One pointer in each array or string, moving the one that's behind.
i = 0 ; j = 0
while i < len(a) and j < len(b):
compare a[i] and b[j], move the smaller (or both)Used for: intersections of sorted arrays, merging, Long Pressed Name, Backspace String Compare (from the back).
3. Zones in place. Pointers mark where each group ends, and values are swapped into the right zone, like Move Zeroes in chapter 1 or Sort Colors here.
02How to spot it
- The input is sorted, or sorting it first is fine.
- You're looking for a pair (or triplet) with some sum or property.
- The question says "in place" or "O(1) extra space".
- Something should read the same from both ends.
03Why it's safe to skip choices
The key question for every two-pointer solution: why can I move this pointer without missing the answer? In a sorted array, if a[l] + a[r] is too small, then a[l] with anything left of r is even smaller, so a[l] can never be part of the answer. Discarding it is safe. Interviewers will ask you to say this out loud.
04Problems in this chapter
Valid Palindrome, Two Sum II and Intersection of Two Arrays are free to start with. Then: Backspace String Compare, Long Pressed Name, Maximum Ascending Subarray Sum, Sort Colors, Container With Most Water, 3Sum, 4Sum, and Max Consecutive Ones III, which leads into the next chapter, Sliding window.