ProgrammingHard

An array of 2 x 10^5 records must be answered with 2 x 10^5 queries, each asking how many records have key <= q. Which approach is correct and fast enough?

  1. A. Scan the whole array for each query, about 4 x 10^10 steps
  2. B. Sort the keys before every query, about 4 x 10^10 steps
  3. C. Sort the keys once, then answer each query by binary search, about (N + Q) log N total
  4. D. Use a linked list and walk it for each query, about 4 x 10^10 steps

Correct answer: C. Sort the keys once, then answer each query by binary search, about (N + Q) log N total

Sorting once and using a binary search per query costs O((N + Q) log N), about 7 x 10^6 steps. A linear scan per query is O(NQ), about 4 x 10^10.

More C Programming questions

Exams that ask this topic