Microsoft Interview Question

int getCount(int[] arr, int num)

Interview Answers

Anonymous

Nov 2, 2011

binary search twice get two indices, and number = n1 - n2 +1;

Anonymous

Sep 15, 2012

It can be logn. First look for num - 1, get n1, then look for num + 1, get n2. Here comes a trick. Here is the binary search we should use, while(start <= end){ // do what normal binary search should do. } //if num - 1 or num + 1 is not in the array. return start - 1;

Anonymous

Aug 19, 2010

binary search in logN

Anonymous

Oct 19, 2011

Worst case can not be log(n) since the number of occurrence is asked. You can find the exact place you have to start with binary search but you have to count occurrence as well. If the array has only one distinct element, you have to go over the whole array which becomes O(n) in the worst case.