Two Pointers
Two positions describe the part of a sequence still relevant. Each safe pointer move removes candidates or extends an established prefix.
Picture the idea
Two people compare price tags from opposite ends of a sorted shelf. A sum that is too low rules out the cheaper tag with every remaining partner.
When to use it
Use a sorted order to discard candidates, or separate read and write positions during in-place compaction.
How it works
In [1, 3, 6, 8] with target 9, begin at 1 and 8. If the target were 11 instead, a sum of 9 would let the left pointer move inward.
- Compare the two endpoint values.
- Advance the pointer justified by the invariant.
- Write the next retained value into the compacted prefix.
Two monotonically advancing endpoints make at most O(n) moves in total and need O(1) pointer space.
Watch for this mistake
Pair-sum elimination by magnitude fails on unsorted values.
Explain why every skipped pair is impossible before moving a pointer.