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?

  1. A. Walk from the head for every query, about 5 x 10^9 steps
  2. B. Walk the list into an array once in O(n), then answer each query by indexing in O(1)
  3. C. Sort the nodes before each query, about 10^11 steps
  4. 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

Exams that ask this topic