Given a sorted array of integers, how can we find a pair of integers that sum to K?
e.g. array = 1,3,5,6,0
, K = 6
, the answer is 1 and 5.
Time complexity should be minimized.
Given a sorted array of integers, how can we find a pair of integers that sum to K?
e.g. array = 1,3,5,6,0
, K = 6
, the answer is 1 and 5.
Time complexity should be minimized.
There is a linear (O(n)) solution.
Take a hashtable and while iterating through the array check if the current element is already in the hashtable - if so then you've found the answer. Otherwise insert the number which is equal to K minus the current element. Works for non sorted array, btw.
You may want to look at this blog post:
http://www.codingatwork.com/2011/07/array-sum/
My approach would be to do a binary search of the list for
K/2
, then walk one variablea
left and another variableb
right trying to find a solutiona+b=K
.The idea would be to start
a
at the largest number less than or equal toK/2
and startb
at the smallest number greater thana
. Again, use a binary search to finda
and letb
be the next element in the array. Thena+b = K
, thenreturn (a,b)
.a+b < K
, then moveb
to the right one position.a+b > K
, then movea
to the left one position.Of course, you can skip the binary search and just start
a
at the beginning of the array andb
at the end of the array, and then doa+b = K
, thenreturn (a,b)
.a+b < K
, then movea
to the right one position.a+b > K
, then moveb
to the left one position.This is probably faster.