Amazon Interview Question
Development Support EngineersHow??
You have to find the FIRST occurrence of 1, with Binary search, when you start in middle, and there is a 1, it will exit. You dont want that.
You need to modify the binary search little bit such that the if the middle element happens to be a 0 then if the number right next to it is 1 then u conclude that is the first one else if the middle number happens to be a 1 then if the number left to it is a 0 then u can conclude its the first one...if none of these is the case then u recurse the same process of the left half if the middle number happens to be a one or the right half if the number happens to be a zero. Its technically Binary search paradigm . Hope that helps.
Add all the numbers , suppose u get x.This takes O(N).
Now suppose size of array is n , now index to n-x. This is O(1).This is the 1st one.This works as array is sorted and zeros come first.
could someone clarify,
if the sequence is sorted then all 0's would obv appear first and then followed by 1's are they asking us to find the occurrence of the first "1" in the array,is that the question?
If the answer to my previous question is "yes" then are we required to find a method which takes < O(n).If its an O(n) solution then I am sure all of us know more than one method to do this qn.
Using a modified version of the binary search algorithm, you can return the lower bound index when the lower bound has the key being searched in case when the upper bound is greater than or equals to the key.
firstOccurrance(int[] sortedBins) {
int lower = 0;
int upper = sortedBins.length - 1;
while (lower <= upper) {
int middle = 1 + (upper - lower) / 2;
if (sortedBins[middle] == 0) {
lower = middle + 1;
} else {
upper = middle - 1;
}
if (sortedBins[lower] == 1) {
return lower;
}
}
return -1;
}
#include<stdio.h>
#include<math.h>
int BinarySearch(short int* array, int end) {
int mid;
int start=0;
while(start<=end) {
mid=(start+end)/2;
if(array[mid]==0 && array[mid+1]==1)
return mid+2;
else if(array[mid]==1 && array[mid-1]==0)
return mid+1;
else if(array[mid]==0)
start=mid+1;
else if(array[mid]==1)
end=mid-1; }
return -1; }
int find(short int* array) {
int i=0;
long long index=0;
while(array[index]!=1) {
i++;
index=pow(2,i); }
i=BinarySearch(array,index);
return i; }
O(loglogn) - Interpolation Search- not recommended as points are not equally iid (Independent and identically-distributed )
- YetAnotherCoder October 13, 2008O(Logn) - Binary Search : Could not be so dumb question
Not able to scrutinize the exploitation of 0's 1's , Hashing wouldn't help.
Please comment.