Yahoo Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
A fairly simple question. I proposed 3 approaches:
1) Brute Force: For each element in the array search all the remaining elements for (Sum - the chosen element). O(N^2) is the Time Complexity.
2) (a) Sort the array and use 2 references one from the start and the other from the end.
(b) If sum of both the referenced element is less than given sum then increment the position of the smaller reference.
(c) If sum of both the referenced element is greater than given sum then decrement the position of the larger reference.
(d) Repeat (b) & (c) until both references cross each other.
O(N*Log N) - For Sorting + O(N) searching with references = Total (N*Log N)
3) Use a HashTable (assume a HashMap). In the first pass, put each element into the HashTable. In the second pass, for each element, search for the element (Sum - current element). At the end of the two passes we will have our solution.
Time Complexity is O(N)
I was asked to assume memory is a constraint, so ended up writing code for the proposal (2) using Sorting.
If array is sorted this could be solved in O(n) complexity.
Python solution:
def pair_of_sum(A, S):
left = 0
right = length(A) - 1
while left < right:
current_sum = A[left] + A[right]
if current_sum == S:
return left, right
if current_sum < S:
left += 1
if current_sum > S:
right -= 1
If array is not sorted we need to sort it and total complexity will be O(n log n)
there are three ways of aproach
int[] input={2,7,5,3,0,8,1};
int traget=9;
//if no extra memmory is allowed
for(int i=0;i<input.length;i++)
{
for(int j=i+1;j<input.length;j++)
{
if(traget==input[i]+input[j])
{
System.out.println("sol 1 Pair with given sum " +
traget + " is (" + input[i] +
", "+input[j]+")");
}
}
}
//if no idea about maximum element
Hashtable<Integer,Integer>indexvaluemap=new Hashtable<Integer, Integer>();
for (int i = 0; i < input.length; i++) {
indexvaluemap.put(input[i],i);
}
for(int i=0;i<input.length;i++)
{
if(indexvaluemap.get(traget-input[i])!=null&&indexvaluemap.get(traget-input[i])!=i)
{
System.out.println("sol2 Pair with given sum " +
traget + " is (" + input[i] +
", "+(traget-input[i])+")");
}
}
//if maximum value of elements in an array is known
int MAX = 100000;
boolean[] binmap = new boolean[MAX];
for (int i=0; i<input.length; ++i)
{
int temp = traget-input[i];
// checking for condition
if (temp>=0 && binmap[temp])
{
System.out.println("sol3 Pair with given sum " +
traget + " is (" + input[i] +
", "+temp+")");
}
binmap[input[i]] = true;
}
Sergey is right. Just adding another interesting mix :
- NoOne October 30, 2016