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 once, I will propose an implementation in C++.
size_t count(std::vector const& vec, int key)
{
auto p = std::equal_range(vec.begin(), vec.end(), key);
return std::distance(p.first, p.second);
}
equal_range
uses a binary search, the result is equivalent to:
std::make_pair(std::lower_bound(vec.begin(), vec.end(), key),
std::upper_bound(vec.begin(), vec.end(), key));
but the implementation should makes it slightly faster, even though all are in O(log N) (in terms of number of comparison).