Two Pointers: Two pointers and monotone movement
Goal: Learn the pattern first, then apply it to the 6 roadmap problems in this chapter.
When this pattern appears
The data is sorted, lies on two ends of a sequence, or can be partitioned in one pass.
The reusable idea
Prove why moving one pointer cannot skip the optimal answer. Keep a clear invariant for each region.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
Which pointer can be discarded based on the current comparison, and why is that safe?
Common failure modes
Pointer crossing, duplicate handling, and whether the input is sorted or may be mutated.
Chapter problems from the workbook
- #10 · Valid Palindrome — Day 5, Easy. Open problem ↗
- #11 · Two Sum II - Input Array Is Sorted — Day 5, Medium. Open problem ↗
- #12 · Sort Colors — Day 6, Medium. Open problem ↗
- #13 · 3Sum — Day 6, Medium. Open problem ↗
- #14 · Container With Most Water — Day 8, Medium. Open problem ↗
- #15 · Trapping Rain Water — Day 8, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.