Learn the Two Pointers technique for efficient array searches and manipulations. Interactive visualization of the converging pointers strategy.
About this algorithm
The two pointers technique walks two indexes through an array at once, so a problem that looks like it needs every pair is solved in one O(n) pass. For a pair sum in a sorted array, one pointer starts at each end: if the sum is too small the left pointer moves right, and if it is too big the right pointer moves left. It finds the pair, or proves there is none, without ever going back.
Use it when the array is sorted (or you can afford to sort it) and the question is about a pair: a pair with a given sum, the closest sum, a pair with a given difference. If the array is unsorted and you need the original positions, the hash map two sum page is the better tool, since it needs no sorting. The sliding window pages also use two indices, but both move in the same direction to mark out a stretch of the array; here they come from opposite ends. The other two pointer pages (valid palindrome, container with most water, trapping rain water) use the same inward walk with their own rule for when the pointers move: valid palindrome moves both together, while container with most water and trapping rain water move only the shorter side.
Set left = 0 and right = n - 1. The pair being tested is always array[left] and array[right].
Add the two values. If the sum equals the target, return [left, right].
If the sum is below the target, array[left] is too small even with the biggest value still in play, so it cannot be part of any answer. Drop it with left++.
If the sum is above the target, array[right] is too big even with the smallest value still in play. Drop it with right--. Keep going while left < right; when they meet, no pair exists.
The page rolls a fresh sorted row of 10 numbers each time and sets the target to the third value plus the eighth, so a pair always exists. Take the row [4, 9, 15, 22, 30, 41, 47, 58, 66, 90], which gives a target of 15 + 58 = 73. 4 + 90 = 94 is too big, so right moves to 66. 4 + 66 = 70 is too small, so left moves to 9. 9 + 66 = 75 is too big, so right moves to 58. 9 + 58 = 67 is too small, so left moves to 15. 15 + 58 = 73: the pair is at indices [2, 7], found after 5 sums and 4 moves. Checking every pair would take up to 45 sums on 10 values.
Each move throws away one value together with every pair it could still form, and the argument above shows none of those pairs can hit the target. So the walk never skips the answer, and it ends after at most n - 1 moves.
Time: every step moves one pointer one place inward, so there are at most n - 1 steps before they meet. Space: two indices and a running sum, whatever the size of the array.