This was asked in on-site Microsoft interview.
Count the number of occurrences of a given key in an array.
I answered linear search because the elements may be s
** Time Complexity = O ( lg N ) where N is the size of array
** Arguments for binarySearchXXXXX:**
**
package array;
public class BinarySearchQuestion {
public static int binarySearchFirst(int[] array, int k) {
int begin = 0;
int end = array.length-1;
int mid = -1;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (array[mid] < k) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
//System.out.println("Begin index :: " + begin + " , array[begin] " + array[begin]);
return (begin <= array.length - 1 && begin >= 0 && array[begin] != k) ? -1 : begin;
// return begin;
}
public static int binarySearchLast(int[] array, int k) {
int begin = 0;
int end = array.length - 1;
int mid = -1;
while (begin <= end) {
mid = begin + (end - begin) / 2;
if (array[mid] > k) {
end = mid - 1;
} else {
begin = mid + 1;
}
}
//System.out.println("Last index end :: " + end + " , array[mid] " + array[end]);
return (end <= array.length - 1 && end >= 0 && array[end] != k) ? -1 : end;
//return end;
}
/**
* @param args
*/
public static void main(String[] args) {
// int[] array = { 0, 1,1,1, 2, 3, 4,4,4,5, 5, 5, 5, 5, 5, 5, 5, 5, 5,5,6,6,6,6, 6, 7, 7, 7,
// 7, 8, 9 };
// int[] array = {-1, 0,1, 1,1,2,3};
int[] array = {1,1,1};
int low = binarySearchFirst(array, 1);
int high = binarySearchLast(array, 1);
int total = (high >= low && low != -1 && high != -1) ? ( high - low + 1 ): 0;
System.out.println("Total Frequency " + total);
}
}