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?- A. [1, 2, 3, -1, 4]
- B. [1, -1, 3, 1, -1]
- C. [1, -1, 3, -1, 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
- Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs. python class T: def…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with…
- Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be…
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…