Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?
Constraints: This should be done in O(n) and in-place (without any external storage like arrays, hash-maps) (you can use extra variables/pointers)
If this is not possible, can there be a proof given for the same?
I was asked this same question during an interview, and this is the scheme I had in mind. There's an improvement left to do, to permit negative numbers, but it would only be necessary to modify the indexes. Space-wise ain't good, but I believe running time here would be O(N)+O(N)+O(subset of N) -> O(N). I may be wrong.
Critics are welcomed.
In java, this is depends on max number in array. it returns an int[] having the indexes of two elements. it is O(N).
My solution in Java (Time Complexity O(n)), this will output all the pairs with a given sum
Here is a solution witch takes into account duplicate entries. It is written in javascript and runs using sorted and unsorted arrays. The solution runs in O(n) time.
Start at both side of the array and slowly work your way inwards keeping a count of how many times each number is found. Once you reach the midpoint all numbers are tallied and you can now progress both pointers counting the pairs as you go.
It only counts pairs but can be reworked to
Enjoy!
If you have a sorted array you can find such a pair in O(n) by moving two pointers toward the middle
The sorting can be made O(N) if you have a bound on the size of the numbers (or if the the array is already sorted in the first place). Even then, a log n factor is really small and I don't want to bother to shave it off.
proof:
If there is a solution
(i*, j*)
, suppose, without loss of generality, thati
reachesi*
beforej
reachesj*
. Since for allj'
betweenj*
andj
we know thata[j'] > a[j*]
we can extrapolate thata[i] + a[j'] > a[i*] + a[j*] = target
and, therefore, that all the following steps of the algorithm will cause j to decrease until it reachesj*
(or an equal value) without givingi
a chance to advance forward and "miss" the solution.The interpretation in the other direction is similar.
An
O(N)
time andO(1)
space solution that works on a sorted array:Let
M
be the value you're after. Use two pointers,X
andY
. StartX=0
at the beginning andY=N-1
at the end. Compute the sumsum = array[X] + array[Y]
. Ifsum > M
, then decrementY
, otherwise incrementX
. If the pointers cross, then no solution exists.You can sort in place to get this for a general array, but I'm not certain there is an
O(N)
time andO(1)
space solution in general.