ProgrammingHard

A sorted array of 10^6 keys answers 10^5 queries of the form 'how many keys lie in [L, R]'. Which approach is correct and fast enough?

  1. A. Two binary searches per query, for lower and upper bounds, O(log n) each
  2. B. A full scan per query, about 10^11 steps
  3. C. Re-sorting before each query, about 10^11 steps
  4. D. A nested loop over pairs of keys, about 10^12 steps

Correct answer: A. Two binary searches per query, for lower and upper bounds, O(log n) each

Binary search finds both ends of the range in O(log n) per query, about 4 x 10^6 steps in total. A scan per query is far too slow.

More C Programming questions

Exams that ask this topic