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
For unsorted array there is not much we can do other than linear search.
For sorted array you can do it in O(logN)
using a slightly modified binary search:
key
, call it f
.key
, call it l
.key
exists in the array l-f+1
is the answer.Finding the first occurrence:
arr[i]
is the first occurrence of key
iff
arr[i] == key
and either
i == 0
( it's the first element of
the array) orarr[i-1] != key
(it's not the first
element of the array and element to
it's left is different)You can slightly modify the binary search to find the first occurrence.
In a binary search you terminate the search when you find arr[mid] == key
.
Modify the condition such that you terminate the search when you find the first occurrence instead of any occurrence.
Algorithm:
low = 0
high = arrSize - 1
while low <= high
mid = (low + high) / 2
//if arr[mid] == key // CHANGE
if arr[mid] == key AND ( mid == 0 OR arr[mid-1] != key )
return mid
//else if ( key < arr[mid] ) // CHANGE
else if ( key <= arr[mid] )
high = mid - 1
else
low = mid + 1
end-if
end-while
return -1
Similarly you can find the last occurrence.