ProgrammingHard

A singly linked list of N = 10^6 nodes must answer 10^6 queries for the value at position k. Which approach is correct and fast enough?

  1. A. Walk the list from the head for every query, about 5 x 10^11 steps
  2. B. Sort the list before every query, about 10^12 steps
  3. C. Copy the values once into an array, then index it in O(1) per query
  4. D. Scan the whole list and rebuild it for each query

Correct answer: C. Copy the values once into an array, then index it in O(1) per query

A single O(N) copy makes every query O(1), total about 10^6 steps. Walking the list each time costs about N^2 / 2 = 5 x 10^11.

More C Programming questions

Exams that ask this topic