ProgrammingHard
A linked list holds 10^5 nodes and must answer 10^5 queries for the k-th node. Which approach is correct and fast enough?
- A. Walk from the head for every query, about 5 x 10^9 steps
- B. Walk the list into an array once in O(n), then answer each query by indexing in O(1)
- C. Sort the nodes before each query, about 10^11 steps
- D. Rebuild the list for each query, about 10^10 steps
Correct answer: B. Walk the list into an array once in O(n), then answer each query by indexing in O(1)
One O(n) copy into an array makes all later queries constant time. Walking per query costs about n^2 / 2 steps.
More C Programming questions
- An in-place sort on 10^6 ints must not use more than a few kilobytes of extra memory. Which algorithm fits?
- A quicksort with a poor pivot choice on already sorted input of n elements has what time?
- A hash table with 2^20 slots holds 2 x 10^5 keys and uses a good hash. What is the expected cost of a successful lookup?
- For n = 10^5, which expression correctly counts the pairs (i, j) with i < j where a[i] + a[j] equals a target, in O(n log n) time?
- A recursive function is called with depth 10^6 in C on a typical 8 MB stack with 64-byte frames. Is this safe?
- A bit set of 64 flags is packed in one unsigned long long. Which expression tests flag 17?