ProgrammingModerateTCS NQT · Accenture

A sorted array holds 10^6 integers and receives 10^5 queries asking how many values are at most x. Which approach is fastest in CPython?

  1. A. Scan the whole array for each query, about 10^11 comparisons
  2. B. Use bisect_right on the sorted array per query, about 2 x 10^6 steps
  3. C. Sort the array again for each query, about 10^11 steps
  4. D. Build a new set of values for each query, about 10^11 steps

Correct answer: B. Use bisect_right on the sorted array per query, about 2 x 10^6 steps

bisect_right finds the count of values not above x in O(log n) per query, so 10^5 queries cost about 2 x 10^6 steps. Scanning or re-sorting each time costs about 10^11.

More Python Programming questions

Exams that ask this topic