Two Pointers — Converging
Sorted array, target sum. Put one pointer at each end and walk them toward each other, deciding which to move by comparing the current sum to the target.
When to reach for it: the input is sorted (or you can sort it), and you’re looking for a pair — or a fixed-size combination — that hits, brackets, or counts against a target sum.
The micropattern:
- Sort the array (if it isn’t already).
- Place
leftat the start andrightat the end. - Look at
nums[left] + nums[right]:- too small? move
leftright to grow the sum. - too big? move
rightleft to shrink it. - just right? record it and step both inward.
- too small? move
For 3-/4-sum variants you fix the outer element(s) with a loop and run the converging scan on the rest. Work through the problems below in order — each one adds a small twist.
Two Sum II — Input Array Is Sorted
The canonical converging scan: one pass, no extra memory.
Container With Most Water
Same converging scan, but move the shorter wall to chase a bigger area.
Squares of a Sorted Array
The biggest square is always at one end — fill the result back to front.
Boats to Save People
Sort, then pair the lightest with the heaviest that still fits.
Intersection of Two Arrays
Two pointers across two sorted arrays, advancing the smaller side.
3Sum
Fix one number, then run the converging scan on the rest — plus dedup.
3Sum Closest
Same scan, but track the sum nearest the target instead of an exact hit.
3Sum Smaller
Counting trick: when the sum is small enough, an entire range of pairs counts at once.
4Sum
Two nested anchors, then the same converging scan and dedup.