ProgrammingModerate

A program keeps a set of at most 10^5 ints and answers membership queries 10^5 times. Which structure is correct and fast enough?

  1. A. An unsorted array with a linear scan per query, about 10^10 steps
  2. B. A linked list with a linear scan per query, about 10^10 steps
  3. C. A sorted array with binary search, O(log n) per query after O(n log n) sorting
  4. D. Recompute the set from input for each query, about 10^10 steps

Correct answer: C. A sorted array with binary search, O(log n) per query after O(n log n) sorting

Binary search on a sorted array answers each query in O(log n), about 1.7 x 10^6 steps overall. A scan per query is quadratic.

More C Programming questions

Exams that ask this topic