ProgrammingHard

To answer 'how many times does x appear in a sorted array' in O(log n), which pair of searches is correct?

  1. A. A linear scan from both ends, which is O(n)
  2. B. One binary search that stops at the first x, then counts by scanning
  3. C. Sorting again before each query
  4. D. lower_bound(x) and upper_bound(x), and the answer is their difference

Correct answer: D. lower_bound(x) and upper_bound(x), and the answer is their difference

The difference of the two bounds gives the count in O(log n) time for any number of duplicates.

More C Programming questions

Exams that ask this topic