Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Assuming that the array is sorted:
class Problem1
{
public static void main(String[] args)
{
int[] iArray = {1,3,5,6,7,9};
int len = iArray.length;
int first = 0;
int last = len - 1;
int targetSum = 12;
while(first<last)
{
if(iArray[first] + iArray[last] == targetSum)
{
System.out.println(first + "," + last);
first++;
last--;
}
else if((iArray[first] + iArray[last]) > targetSum)
last--;
else if((iArray[first] + iArray[last]) < targetSum)
first++;
}
}
}
This was posted by someone before for a very similar question:
This will give all existing pairs such that
A[i] + A[j] = k
Method 1: Sort the array and then do the following (O(n log n)):
Method 2: We can use hash table (O(n)):
- themostrandomname September 29, 2013