Walk two indices through ordered data, and at every step, discard the side that cannot improve the answer.
A brute-force scan compares every pair, which costs O(n^2). Two pointers works because order carries information: if the structure is sorted (or has monotonic behaviour), one comparison tells you which side can never improve, so you can discard it forever.
That single decision — move left or move right — is the whole pattern. Each element is visited once, and nothing is ever revisited.
When to use it
Reach for it
- The input is sorted, or you can sort it cheaply.
- You are looking for a pair, triplet, or boundary that satisfies a condition.
- You need to partition, dedupe, or compact in place with O(1) extra space.
- You are comparing a sequence against itself from both ends (palindromes, reversals).
Skip it
- Order is meaningless and cannot be created (use hashing instead).
- You need every qualifying pair, not the existence of one — the discarded side may hide answers.
- The condition is not monotonic, so shrinking one side does not reliably move you toward the target.
- "sorted array" in the first sentence
- "find two numbers that…" / "closest to target"
- "in place" or "O(1) extra space"
- "remove duplicates" or "move all X to the end"
- "is it a palindrome"
The pattern
- 1
Place pointers at the two ends (opposite direction) or both at the start (same direction).
- 2Evaluate the condition at the current pair.
- 3
Move the pointer that cannot possibly improve the result.
- 4Stop when the pointers meet or cross.
Complexity
Each element is visited at most once as the pointers close in.
Just the two indices — no auxiliary structures.
Add up front if you have to sort the input yourself — that then dominates the total cost.
Common pitfalls
Forgetting the input must be ordered
The discard step is only valid under sorted or monotonic input. On unsorted data the pointers silently skip valid answers.
Off-by-one on the loop guard
Use left < right when a pair must be two distinct elements, and
left <= right only when a single middle element is a valid
answer.
Not skipping duplicates
In triplet and unique-pair problems, advance past equal neighbours after recording a hit, or the same answer repeats.
Moving both pointers at once
Unless the condition proves both sides are exhausted, moving both can step over the answer.
Variants worth knowing
- 1
Opposite ends — pair sums, palindromes, container with most water.
- 2
Fast and slow — cycle detection, middle of a linked list.
- 3Read and write — in-place dedupe and compaction.
- 4
Sliding window — same-direction pointers with a running aggregate.