Two Pointers
Replace a pair of nested loops with two indices that each only move forward, cutting O(n²) to O(n).
After this lesson you will be able to
- Explain why checking every pair is O(n²) and what information lets a pointer skip many pairs at once.
- Solve pair and triplet sum problems on sorted arrays with colliding pointers.
- Use the reader/writer (seeker and placeholder) pattern to modify an array in place.
- Merge two sorted sequences with one pointer on each.
- Prove to yourself that discarding a candidate is safe, which is what makes the technique correct.
Before you start. You should be comfortable with array indexing and while loops. Sorting Basics helps because most pointer problems start sorted.