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?
- A. An unsorted array with a linear scan per query, about 10^10 steps
- B. A linked list with a linear scan per query, about 10^10 steps
- C. A sorted array with binary search, O(log n) per query after O(n log n) sorting
- 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
- Which statement about finding the length of a null-terminated C string is correct?
- Which code gives the correct sum of the first n squares, for n up to 10^6, using a closed form in O(1)?
- Which operation on a dynamic array of n elements has O(1) amortised cost when using doubling?
- A loop does for (i = n; i > 0; i /= 2) for (j = 0; j < i; j++) work();. For n = 1024, how many times is work() called in total?
- Which of these is an O(n) method to test whether a string of length n is a palindrome in C?
- char s[] = "hello world"; char w = strchr(s, ' ') + 1; printf("%s", w); What is printed?