Heard from a friend who got asked the following question in an interview:
Given a sorted array of ints, and a target number, find two elements from the array that add up to the target (or determine that no such pair exists) — in linear time.
When I first heard this, I thought: isn’t this the subset-sum problem? Isn’t that NP-complete? How can you do tihs in linear time??
But after thinking about it for a while, it dawned on me. The array is sorted, and we need to find only two elements.
So here’s my home-grown solution:
Assuming that the array, a, is sorted from smallest to largest, and target is the number the pair must add up to:
1. Start from the right to find the largest element in a that is smaller (or equal) than target. Call this index right. Let delta = target - a[right].
2. Now start looking from the left to find the largest element smaller (or equal) than delta. Call this index left.
Now here I’ll claim that the two integers we’re looking for occur within the sub-array a[left..right], or don’t exist at all.

(click on the thumbnail for a larger image)
Let t = target - (a[left] + a[right])
If t=0 then we’ve found our pair.
If t < 0, then the current sum of a[left] and a[right] is more than target. In this case, we’ll look at the next smaller number from the top (the right). So right = right - 1.
If t > 0 then the current sum of a[left] and a[right] is less than target. In this case, we’ll look at the next larger number from the bottom (the left). So left = left + 1.
We do this until either t=0 (in which case we’ve found our pair), or left and right cross each other (in which case such a pair does not exist).
There you have it — a solution in one linear pass over the array. I feel much better now.