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?
- A. Scan the whole array for each query, about 4 x 10^10 steps
- B. Sort the keys before every query, about 4 x 10^10 steps
- C. Sort the keys once, then answer each query by binary search, about (N + Q) log N total
- 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
- After removing duplicate keys from a sorted array of records with the two-index method (keep a[w] when its key differs from the last kept…
- Bubble sort on the records of 4 keys {4, 3, 2, 1} with a swap count: how many swaps are made?
- A struct array holds records with an int key; the program calls qsort with the comparator (int)(a->key - b->key) for keys near INTMAX and…
- A bsearch call uses a key of type int but the array holds struct records with an int field. What is the correct way to compare?
- Which comparator for qsort on int array is correct for ALL int values (no overflow, no wrong sign)?
- int m[3][4]; int f = &m[0][0]; Which expression refers to the same element as m[2][1]?