Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used).

Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used).
from collections import OrderedDict
class LRU:
    def __init__(s, cap): s.c, s.d = cap, OrderedDict()
    def get(s, k):
        if k not in s.d: return -1
        s.d.move_to_end(k); return s.d[k]
    def put(s, k, v):
        s.d[k] = v; s.d.move_to_end(k)
        if len(s.d) > s.c: s.d.popitem(last=False)
c = LRU(3); out = []
for k in (1, 2, 3): c.put(k, k)
out.append(c.get(1)); c.put(4, 4)
out.append(c.get(2)); out.append(c.get(3)); c.put(5, 5)
out.append(c.get(1)); out.append(c.get(4))
print(out)
What is printed?
  1. A. [1, 2, 3, -1, 4]
  2. B. [1, -1, 3, 1, -1]
  3. C. [1, -1, 3, -1, 4]
  4. D. [1, -1, -1, -1, 4]

Correct answer: C. [1, -1, 3, -1, 4]

get(1) refreshes key 1, so put(4) evicts 2 (miss → −1). get(3) refreshes 3, leaving 1 as least recent, so put(5) evicts 1 (−1), and 4 is still present. A FIFO cache would instead evict 1 first and give [1, 2, 3, −1, 4].

More Coding Interview Problems questions

Exams that ask this topic