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?
- A. Two binary searches per query, for lower and upper bounds, O(log n) each
- B. A full scan per query, about 10^11 steps
- C. Re-sorting before each query, about 10^11 steps
- 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
- In a sorted array with duplicates, which index does a lowerbound search return for the key 5 in [1, 5, 5, 5, 8]?
- Two sorted struct arrays of sizes n and m are merged into a new array. How many elements does the merged array hold?
- A struct array of n records is sorted by key. The code stores a record index inside each record before sorting, so that it can recover the…
- A histogram of sorted keys [1, 1, 2, 2, 2, 3] counts the adjacent equal pairs. How many such pairs are there?
- The largest gap between consecutive values of the sorted list 1, 4, 9, 16 is which value?
- The median of the sorted keys 2, 4, 6, 8 with integer division is which value?