Machine Room

Two Pointers

Find two values in a sorted array that add up to a target, in one pass: start one pointer at each end and walk in. The one-page notes from the reel.

Download the PDF

One-page notes, Two Pointers. Find two values in a sorted array that add up to a target, in one pass. 1, The problem. A row of eight cells: 1, 4, 5, 6, 7, 9, 9, 10, tagged prices · sorted low to high, with a green tag target 12. Under it: ? + ? = 12. Given a sorted array and a target sum, find two values that add up to it, or report that no such pair exists. The interview version: LeetCode 167, Two Sum II - Input Array Is Sorted. 2, The slow way: try every pair. The same row; seven orange arcs run from the 1 to each of the other seven cells: the 1 alone: 7 pairs. 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 pairs. With n values, that is n × (n − 1) / 2 pairs: O(n²). It never uses the fact that the array is sorted. 3, The walk: six looks. The row with 1, 4, both 9s and 10 crossed out, 5 and 7 circled in green, 6 plain; the left pointer under the 5 came in from the left end, the right pointer under the 7 came in from the right end. A table, look, sum, verdict, then: 1, 1 + 10 = 11, too small, 1 is out, left steps in. 2, 4 + 10 = 14, too big, 10 is out, right steps in. 3, 4 + 9 = 13, too big, 9 is out, right steps in. 4, 4 + 9 = 13, too big, the other 9 is out, right steps in. 5, 4 + 7 = 11, too small, 4 is out, left steps in. 6, 5 + 7 = 12, found, the pair: 5 and 7. Found in 6 looks instead of 28 pairs. 4, The rule, and why it is safe. sum < target → too small → left steps right. sum > target → too big → right steps left. sum = target → found. Too small: the left value is paired with the biggest value left and still falls short, so it can't make the target with anything. It's out. Too big: the right value is paired with the smallest value left and is already too much. It's out. Every look throws one value out for good, so the pointers only move toward each other. If they meet without a match, there is no such pair. 5, In code. def pair_sum(a, target): left, right = 0, len(a) - 1; while left < right: s = a[left] + a[right]; if s == target: return a[left], a[right]; if s < target: left += 1; else: right -= 1; return None. pair_sum([1, 4, 5, 6, 7, 9, 9, 10], 12) → (5, 7). 6, The cost. A table, every pair against two pointers: 8 values, 28 pairs, at most 7 looks. 30,000 values, 449,985,000 pairs, at most 29,999 looks. Time, O(n²), O(n). Not sorted? Sort first. Then the total is O(n log n): the sort costs more than the walk. Extra memory: O(1), just two indexes. Same family: two pointers moving the same way at different speeds is the sliding window. Sorted array, pair question? Start at both ends and walk in.

On a phone, press and hold the image to save it. The reel: Two Pointers Explained: Find a Pair in One Pass.