ProgrammingModerate
Which operation makes a sorted array of n elements support lookup in O(log n) and insertion in O(n)?
- A. A hash table with chaining, since it is always sorted
- B. A singly linked list, because lookup is O(1) on a sorted list
- C. A stack, which gives O(log n) insertion
- D. A sorted array with binary search for lookup and memmove for insertion
Correct answer: D. A sorted array with binary search for lookup and memmove for insertion
The array can be searched by bisection. Inserting in the middle shifts elements, which costs O(n) per insert.
More C Programming questions
- For a char buffer of length 10^6 that is processed once, which loop is correct and fast enough?
- A matrix of 3000 x 3000 cells is read once and each cell is visited a constant number of times. Which complexity bound applies to the…
- A recursive merge sort on 10^6 elements makes how many comparisons, roughly?
- Which function call costs O(n) time per call and can be avoided by caching its result in a loop?
- A recurrence T(n) = 2 T(n/2) + n describes which algorithm, with which complexity?
- For a number n up to 10^18 read as a decimal string, what is the number of digits, computed with one pass?