Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: In-Person
void sumTwo(int *arr, int size, int sum)
{
int first, second;
for(int i = 0; i < size; i++)
{
if(arr[i] <= sum)
{
first = arr[i];
for(int j = i + 1; j < size; j++)
{
second = arr[j];
if((second + first)==sum)
{
cout << first << " " << arr[j] << endl;
int temp = arr[j];
arr[j] = arr[i+1];
arr[i+1] = temp;
j = size;
//i++;
}
}
}
}
}
for every element i in aray
For every element i search another element sum-i in array. ( o(n) for searching )
total complexity - o(n^2)
Can be reduced with fast searching algorithms)
the interviewer expected for a more efficient way. You can sort it first to be in ascending order. then look at the sum of the first and last element. if greater than the certain value, check the sum of the first element and second to the last element. if smaller, check the sum of 2nd and the last. In this way you need to only go through the sorted array once.
User hashset to store the array and check if sum-i exists. However, for the case when sum is 2, and i=1. In that case sum=i+i need to be dealt with,
User hashset to store the array and check if sum-i exists. However, for the case when sum is 2, and i=1. In that case sum=i+i need to be dealt with,
In case of hash set we also need to deal with case where i=sum/2 in that case sum= i+ i...
I think a custom impl of hashset can solve the problem. Where repeated numberd will chained to the same hashcode.
In case of hash set we also need to deal with case where i=sum/2 in that case sum= i+ i...
I think a custom impl of hashset can solve the problem. Where repeated numberd will chained to the same hashcode.
In case of hash set we also need to deal with case where i=sum/2 in that case sum= i+ i...
I think a custom impl of hashset can solve the problem. Where repeated numberd will chained to the same hashcode.
without sorting can we just add the first element to all the elements one by one and store the values in the hash map,and the second with third and soon upto last element.till n-1 elemnts and store the values in the hash table.this hash table may need o(n(n-1)/2) time to construct but than the look up for any sum would be just o(1) times.
please,let me know if i am wrong.thanks in advance
Here is a Recursive version:
...
void FindSumOfPairs( int a[], int n, int sum )
{
if( --n == 0 )
return;
FindSumOfPairs( &a[1], n, sum );
for( int i = 0; i < n; i++ )
{
if( a[0] + a[i+1] == sum )
cout << a[0] << "+" << a[i+1] << "=" << sum << endl;
}
}
...
int a[] = { 9, 6, -2, 1, -3, 7, -5 };
int n = 7;
FindSumOfPairs( &a[0], n, 4 );
...
This problem can be solved in O(n) time.
- VadimM April 09, 2012