Two Pointers
Easy+60 XPFind a pair summing to a target in a sorted array by converging two pointers.
Where it breaks
Two pointers only works on a SORTED array.See what happens when you don't.
No visualization loaded.
Watch
—
Press Run to begin.
Two pointers is a neat trick for sorted arrays: put one finger on the smallest value (far left) and one on the largest (far right), and add them. Too big? Move the right finger left to a smaller number. Too small? Move the left finger right to a bigger one. The two fingers walk toward each other until they hit the pair you want — in one pass, no nested loops.
▸Why two pointers instead of just trying every pair?
Trying every pair means a loop inside a loop — for n boxes that's about n×n checks (O(n²)), which explodes on big data. Two pointers makes ONE sweep from both ends: each step moves a finger inward, so you do at most n steps total (O(n)). Same answer, dramatically less work.
▸Why does moving a finger inward actually make sense?
Because the array is sorted. If the current sum is too big, the only way to shrink it is to drop the largest number in play — so move the right finger left. If it's too small, grab a bigger number — move the left finger right. Each move provably rules out pairs you no longer need to check. (Sound familiar? It's the same 'sorted lets me rule things out' idea as binary search.)
▸What if the two fingers meet without finding a pair?
Then no pair sums to the target — and you can be sure, because every move eliminated only pairs that couldn't possibly work. When left and right cross, the search space is empty, exactly like lo passing hi in binary search.
▸Does this also need a sorted array?
Yes. The whole 'too big → move right finger left' logic depends on bigger numbers being on the right. On unsorted data the fingers can walk straight past a valid pair. Hit 'Where it breaks' below to watch exactly that happen.
How the work grows
O(n) is fair — grows in step with the data. Each step moves one finger inward, so the two fingers meet after at most n steps — one sweep. The brute-force 'try every pair' would be O(n²); this is the straight-line win.
Faint dotted lines = O(1) (flat) and O(n) (straight) for comparison.