## Interview Question

Interview Seattle, WA

`Amazon.com`

## given a sorted list of integers, how would you find whether

2 integers exist that add up to a given sum?

## Interview Answer

2 Answers

Have two pointers one pointing to the beginning of Array and the other pointing to the end of array. Try to traverse the first pointer forward and the second one in reverse direction. Eg:- Array -->123456789. Search for sum 9 1.P1 points to 1 , P2 points to 9 2.Add value(P1) + value(P2). Compare with 9. If the sum is equal, then these are the integers If the sum is less, move P1 further but not P2 If the sum is more, move P2 further but not P1. 3.Do the step 2 till P1 is >= P2. Advantages 1.This method takes good advantage of the fact that array is sorted 2.You can find out multiple pairs in one iteration

## Add Answers or Comments

To comment on this, Sign In or Sign Up.

Here's a fairly simple solution in C# (certainly not the most efficient, but simple). static bool sumOfTwo(int[] arr, int sum, ref int num1, ref int num2) { int len = arr.Length; if (len < 2) return false; if ((arr[len - 1] + arr[len - 2] < sum) || (arr[0] + arr[1] > sum)) return false; for (int i = 0; i < len; i++) { if (arr[i] + arr[len - 1] < sum) continue; for (int j = 0; j < len; j++) { if (i == j) continue; if (arr[i] + arr[j] == sum) { num1 = arr[i]; num2 = arr[j]; return true; } if (arr[i] + arr[j] > sum) break; } } return false; }