5

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,10, K = 6, the answer is 1 and 5.

Time complexity should be minimized.

trincot
  • 317,000
  • 35
  • 244
  • 286
akshay
  • 5,235
  • 14
  • 39
  • 49
  • sounds a lot like this blog post that's been making the rounds today: http://www.codingatwork.com/2011/07/array-sum/ – evan Jul 17 '11 at 06:04
  • Does the academic policy of your university and the policy of your professor allow you to ask people on the internet to answer your homework questions? – Dan Grossman Jul 17 '11 at 06:04
  • This question has been asked a million times before..even on here. Please at least do a google search before posting a question.As far as the solution goes..to minimize time use a hashtable. To minimize space..sort the array, have two pointers each pointing to one end and increment and decrement them as required. – Kakira Jul 17 '11 at 06:39
  • 2
    You're saying you have a sorted array. But the example array isn't sorted. Which is it? – svick Jul 17 '11 at 13:46

3 Answers3

7

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 variable a left and another variable b right trying to find a solution a+b=K.

The idea would be to start a at the largest number less than or equal to K/2 and start b at the smallest number greater than a. Again, use a binary search to find a and let b be the next element in the array. Then

  • If a+b = K, then return (a,b).
  • If a+b < K, then move b to the right one position.
  • If a+b > K, then move a to the left one position.

Of course, you can skip the binary search and just start a at the beginning of the array and b at the end of the array, and then do

  • If a+b = K, then return (a,b).
  • If a+b < K, then move a to the right one position.
  • If a+b > K, then move b to the left one position.

This is probably faster.

PengOne
  • 48,188
  • 17
  • 130
  • 149
4

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.

int[] ar = new int[] { 1, 4, 3, 5 };
int K = 6;

HashSet<int> set = new HashSet<int>();
foreach (int a in ar)
{
    if (set.Contains(a))
    {
        Console.WriteLine(a + ", " + (K - a));
        break;
    }

    set.Add(K - a);
}
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0
function findpairzero(arr) {
 let left = 0;
 let right = arr.length - 1;

 while (left < right) {
 if (arr[left] + arr[right] === 0) {
  return [arr[left], arr[right]];
  } else if (arr[left] + arr[right] > 0) {
  right--;
  } else {
  left++;
 }
}
}

console.log(findpairzero([-4, -3, -2, -1, 0, 3, 2, 4, 5]));