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?
- A. Walk the list from the head for every query, about 5 x 10^11 steps
- B. Sort the list before every query, about 10^12 steps
- C. Copy the values once into an array, then index it in O(1) per query
- 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
- A function frees an entire list and then sets head = NULL. Why is setting head to NULL useful?
- Which kind of list makes it O(1) to delete a node given only a pointer to that node?
- In a singly linked list, which operation takes O(1) time when a pointer to the head is given?
- Two pointers walk a linked list: fast goes two nodes per step, slow goes one. The list has an even number of nodes N = 8 and no cycle…
- A cyclic list has a head node whose next points back to itself. What does a naive while (p) loop starting from head do?
- In C, what is the value of a freshly malloc'd int that the program never initialises?