Foundations · Unit 3
Two Pointers
You have an array and you need to find two numbers that add up to a target, or check whether a word reads the same backwards, or push all the zeros to the end. The reflex is a nested loop: for each element, walk the rest of the array. That works, but it is quadratic. On ten thousand elements it is fifty million steps, and it gets worse fast.
The two pointers technique replaces that nested loop with two indices that walk the array intelligently. Instead of comparing every pair, you move the pointers based on what you learn, so each element is visited a small, constant number of times. That drops the work from n squared down to n. The catch is that it only works when the data has some structure you can lean on, usually that it is sorted, or that you can split the array into a part you have finished and a part you have not.
There are two shapes to recognize. In the first, the pointers start at opposite ends and move toward each other. In the second, both start at the front and one races ahead of the other. This unit walks through both, and more importantly, teaches you to feel which one a problem is asking for, and when two pointers is the wrong tool entirely.
You’re not signed in. Your progress here won’t be saved.
The pain: checking every pair
Take the sorted array [1, 3, 5, 8, 11] and the question "do any two numbers add up to 14?" The obvious move is to pick each number and loop through the rest looking for its partner. Pick 1, scan for 13. Pick 3, scan for 11, found it.
That is a nested loop, and for n numbers it does roughly n times n over 2 comparisons. The array being sorted was a gift, and the nested loop throws it away. Two pointers is about not wasting that gift.
You compare every pair in an array of n elements using two nested loops. Roughly how many pairs do you check?
The drills and graded test are premium
The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:
- ✓3 applied drills: train spotting when the concept applies
- ✓A 5-question graded test to clear the unit
- ✓The full guided problem ladder with faded hints, plus the cold-read capstone
From $6/month. Cancel anytime.