Pattern 01👉Arrays & stringsEasy–Medium
Two Pointers
Walk in from both ends of a sorted list and throw away half the work with every step.
Start with the obvious way
A café’s menu is sorted from cheapest to priciest: `[1, 3, 4, 6, 8, 9, 11, 14]`. You have a £13 gift card and want to spend it exactly on two different items. The obvious way is to try every pair — the first item with each of the others, then the second with each of the rest, and so on.
Run it to see the costTwo Pointers, one step at a time
Watch one pointer at each end. Every check rules out a whole row of pairs, not just one.
🧪 Change the target to 20, or to 2, and replay. Where do the pointers stop?
The shape you’ll reuse
Tap a note to see its line.
- line 2Start at both ends — the smallest and largest values in play.
- line 3Stop when they meet: every pair has been ruled in or out.
- line 5Found it — return the positions (or the values).
- line 7Too small: the left value can’t reach the target with anything left, so drop it.
- line 9Too big: the right value overshoots with anything left, so drop it.
Each step moves one pointer inwards, so there are at most n − 1 steps.
Only two indices and a sum — nothing that grows with the input.
The approach
- Initialize left = 0, right = len-1 (or both at start for fast/slow variant)
- Move pointers based on comparison with target
- Stop when pointers meet or cross
Variants
- Same direction: a write pointer trailing a read pointer, e.g. removing duplicates in place.
- Outside in on one string: compare the first and last characters and move both inwards (palindromes).
Think like the algorithm
Your turn, in Python
Which pattern fits?
Answer everything, then submit
9 of 11 correct passes the lesson and unlocks the next pattern.
Go further on LeetCode
The blueprint’s best problems for this pattern. Start with the easy ones and name the pattern before you code.