Amazon Interview Question: given a sorted list of intege... | Glassdoor

Interview Question

Software Design Engineer In Test Interview Seattle, WA

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


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 sum))
        return false;

    for (int i = 0; i sum)
    return false;

Dan on Sep 25, 2011

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.

1.This method takes good advantage of the fact that array is sorted
2.You can find out multiple pairs in one iteration

Manju on Oct 6, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.