Two Pointers
Read a little, play a little. No scary maths, and no rush.
Two fingers on the array
Place one finger at each end of a sorted array. Their sum too small? The left value is the smallest available — move it right. Too big? The right value is the largest — move it left. Each step discards a whole row of possibilities, so the pair (if it exists) is found in one linear pass. That converging dance is the opposite-ends two-pointer pattern.
Two Sum II: the canonical example
def two_sum_sorted(a, t):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == t:
return [l, r]
if s < t:
l += 1 # need bigger → drop the smallest
else:
r -= 1 # need smaller → drop the largest
return [-1, -1]
Why it works: sortedness means every comparison eliminates one side entirely. No hash map needed, O(1) extra space — the classic follow-up is "now do it without extra memory," and this is the answer.
A trace, step by step
Find two numbers summing to 10 in [1, 3, 4, 6, 8, 11]:
- l = 1, r = 11: sum 12 is too big, so move r left.
- l = 1, r = 8: sum 9 is too small, so move l right.
- l = 3, r = 8: sum 11 is too big, so move r left.
- l = 3, r = 6: sum 9 is too small, so move l right.
- l = 4, r = 6: sum 10. Found it, at positions 2 and 3.
Five steps for six elements. Each step ruled out one value for good.
Why throwing away a side is safe
When the sum is too big, the right value cannot be part of any answer. Every remaining left value is at least as large as the current one (the array is sorted), so pairing the right value with any of them gives a sum that is still too big. The same argument in reverse justifies moving left when the sum is too small. Being able to say this in one sentence is what interviewers mean by "justify your approach."
Same direction: a second flavor
Sometimes both pointers start left and one runs ahead: merging two sorted arrays, removing duplicates in place, or partitioning (move zeroes). Same family, different choreography — one pointer defines the frontier, the other does the work.
The greatest hits to recognize
- 3Sum: fix one element, two-pointer the rest (O(n²) total, skip duplicates carefully).
- Container With Most Water: area limited by the shorter wall — always move the shorter side inward.
- Trapping Rain Water: track left-max and right-max as pointers converge; water fills the lower side.
- Valid palindrome / sorted squares: ends-inward is the giveaway shape.
Common bugs
- Using one element twice. The loop condition must be
l < r, notl <= r, or a single value can be paired with itself. - Forgetting the sorted requirement. On unsorted input the discard argument above is false, and the pattern silently gives wrong answers. Sort first, or use a hash map.
- Skipping duplicate handling in 3Sum. Without skipping equal neighbors, the same triplet is reported several times.
- A pointer that never moves. Every branch of the loop must move at least one pointer, or the loop runs forever.
Remember this
- Sorted + pair/target → opposite ends. Merging/partitioning → same direction.
- Every move must discard possibilities provably — say why the discarded side can't hold the answer.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue