Amazon Interview Question
SDE1sCountry: United States
Interview Type: Phone Interview
I don't quite get this solution. Just from the looks of it, it's O(nlogn + n * n/2) ~ O(n^2).
Also, consider the sorted array like - 3 3 3 3 3 3 3 3 3 4 5 9
acc to step 3a) scanning from 3, first number with value <=6 is 4 with index 9. Total array size 12. Adding their diff 12 - 9 = 3 to index i? what will you gain out of that?
@Roxanne:
Algo is very much O(nlogn)
For each element starting from index 0 to n, it will search another 2*i element which in case of sorted array, can be done in O(logn).
Now, for your test case,
starting from 0th index, 2*a[0] = 2 * 3 = 6 and <= of 6 is 5 whose index is 10.
yes, i m wrong in writing array size to subtract from. it should be (arraySize -1). In this case it is 11.
subtracting 10 from 11 gives 1 and adding this to current index (which is 0) give 0 +1 = 1. So we need to remove only 1 element to get the desired result.
In your this case, as initial numbers are same, so with each additional index you will get count: 2, then 3 then 4 ... but min will remain same 1.
You can break this loop after finding that there can not be minimum than 1 in this case, and in some case minimum will be 0.
Ok cool, got it. Good one. Also, why scan from 0 to n/2? Shouldn't it be 0 to n-1 ?
Not that it has any impact on overall runtime O(nlogn), but still.
I think we will have to scan the whole array till the second last element, otherwise we might miss case like this: 3,3,3,3,3,3,3,3,8,15
Same qns was asked to me. I sorted the array then started from the end comparing with a[0]. If a[0]x2 >= a[end] then fine else keep on decrementing. Answer is the number of decrements made. It passed 3 out of 4 test cases.
int find_min_no_of_elem(int *arr, int size)
{
int i,j, temp;
int index[size];
int count=0;
//Sort the array
for(i=0;i<size;i++)
{
for(j=0;j<size-i-1;j++)
if(*(arr+j) > *(arr+j+1))
{
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
//find the distance
for(i=0;i<size;i++)
{
for(j=i;j<size;j++)
{
if(*(arr+i)*2 < *(arr+j))
{
index[i] = j;
break;
}
else
index[i]=0;
}
}
for(i=0;i<size;i++)
{
if(index[i]!=0)
count++;
}
return count;
}
import java.util.Arrays;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int len = s.nextInt();
int a [] = new int[len],i=0,start=0,start1=0,end=len-1,end1=len-1,count=0,count1=0;
boolean done=false,done1=false;
while(s.hasNextInt())
{
a[i]= s.nextInt();
i++;
if (i==len)break;
}
Arrays.sort(a);
for(i=0;i<len;i++)
{
if(a[end]<=2*a[start])
{
done=true;
}
else
{
count++;
start++;
}
if(a[end1]<=2*a[start1])
{
done1=true;
}
else
{
count1++;
end1--;
}
if(done||done1)
{
if(count<=count1)
System.out.println("Minimu elements to be removed " +count);
else
System.out.println("Minimu elements to be removed " +count1);
break;
}
}
}
}
- SK January 27, 2014