Description
Important enough that it deserves its own article if it doesn't exist already (I didn't find it in a quick search)
I wrote a quick stackoverflow answer for the special case of two values https://stackoverflow.com/questions/11928091/linear-time-algorithm-for-2-sum. It uses a two-pointer method which is a good strategy in general for sorted arrays.
The classic linear time two-pointer solution does not require hashing so can solve related problems such as approximate sum (find closest pair sum to target).
First, a simple n log n solution: walk through array elements
a[i]
, and use binary search to find the besta[j]
.To get rid of the log factor, use the following observation: as the list is sorted, iterating through indices
i
givesa[i]
is increasing, so any correspondinga[j]
is decreasing in value and in indexj
. This gives the two-pointer solution: start with indiceslo = 0, hi = N-1
(pointing toa[0]
anda[N-1]
). Fora[0]
, find the besta[hi]
by decreasinghi
. Then incrementlo
and for eacha[lo]
, decreasehi
untila[lo] + a[hi]
is the best. The algorithm can stop when it reacheslo == hi
.
Do you guys have any objections if I write for that section "author: @jxu"? Well I need some reason to contribute here and not on my personal CF blog. #792