Data Structures & AlgorithmsVery hardProduct company OA

An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order?

An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order?
from collections import OrderedDict
cap, c, miss = 3, OrderedDict(), 0
for op in "A B C A D B E A C".split():
    if op in c: c.move_to_end(op)
    else:
        miss += 1
        if len(c) == cap: c.popitem(last=False)
        c[op] = 1
print(miss, "".join(c))
  1. A. 7 EAC
  2. B. 8 ACE
  3. C. 8 EAC
  4. D. 6 BEA

Correct answer: C. 8 EAC

A hit moves the page to the most-recent end; a miss on a full cache evicts the least recent (front). A B C: 3 misses. A: hit → B C A. D: evict B → C A D. B: evict C → A D B. E: evict A → D B E. A: evict D → B E A. C: evict B → E A C. 8 misses in 9 requests – the re-request of A just before D is what makes B, not A, the next victim. Both get and put are O(1) with a hash map + doubly linked list.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic