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
How about this for the sorted part, with O(logN) time complexity?
int count(int a[], int k, int l, int h) {
if (l>h) {
return 0;
}
int mid = (l+h)/2;
if (k > a[mid]) {
return count(a, k, mid+1, h);
}
else if (k < a[mid]) {
return count(a, k, l, mid-1);
}
else {
return count(a, k, mid+1, h) + count(a, k, l, mid-1) + 1;
}
}