Data Structures & AlgorithmsVery hardAmazon · Microsoft OA

Problem: An LFU cache (capacity 2) evicts the least frequently used key; ties are broken by least recently used. get returns −1 on a miss; get and put both count as a use.

Problem: An LFU cache (capacity 2) evicts the least frequently used key; ties are broken by least recently used. get returns −1 on a miss; get and put both count as a use.
from collections import defaultdict, OrderedDict
class LFU:
    def __init__(s, cap):
        s.cap, s.val, s.freq = cap, {}, {}
        s.groups = defaultdict(OrderedDict); s.minf = 0
    def _touch(s, k):
        f = s.freq[k]; del s.groups[f][k]
        if not s.groups[f] and s.minf == f: s.minf += 1
        s.freq[k] = f + 1; s.groups[f + 1][k] = None
    def get(s, k):
        if k not in s.val: return -1
        s._touch(k); return s.val[k]
    def put(s, k, v):
        if k in s.val: s.val[k] = v; s._touch(k); return
        if len(s.val) == s.cap:
            old, _ = s.groups[s.minf].popitem(last=False)
            del s.val[old]; del s.freq[old]
        s.val[k] = v; s.freq[k] = 1; s.groups[1][k] = None; s.minf = 1
c = LFU(2); out = []
c.put(1, 1); c.put(2, 2); out += [c.get(2), c.get(2)]
c.put(3, 3); out += [c.get(1), c.get(3)]
c.put(4, 4); out += [c.get(3), c.get(2), c.get(4)]
print(out)
What is printed?
  1. A. [2, 2, -1, 3, 3, -1, 4]
  2. B. [2, 2, -1, 3, -1, -1, 4]
  3. C. [2, 2, -1, 3, -1, 2, 4]
  4. D. [2, 2, -1, -1, -1, 2, 4]

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

Key 2 reaches frequency 3, so put(3) evicts key 1 (frequency 1). get(3) lifts key 3 to frequency 2, still below key 2's 3, so put(4) evicts 3. An LRU cache would instead evict 2 at that point and print [2, 2, −1, 3, 3, −1, 4].

More Coding Interview Problems questions

Exams that ask this topic