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?- A. [2, 2, -1, 3, 3, -1, 4]
- B. [2, 2, -1, 3, -1, -1, 4]
- C. [2, 2, -1, 3, -1, 2, 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
- Edge case: A generator expression is consumed twice. python g = (x x for x in range(4)) print(sum(g), sum(g)) What is printed?
- Problem: Sort students by grade (descending), breaking ties by name (ascending), using two passes of Python's STABLE sort. python s =…
- Problem: Find the length of the SHORTEST subarray with sum ≥ k when values may be negative (monotonic deque over prefix sums). python from…
- Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques. python from collections import deque def longest(a, lim)…
- Problem: Count subarrays whose maximum lies in [L, R] in one pass. python def count(a, L, R): lastbad = lastok = -1; res = 0 for i, x in…
- Problem: Shortest path (in steps) from the top-left to the bottom-right cell of a grid where 1 is a wall, if you may remove at most k…