LRU cache simulator
Problem
Simulate an LRU cache with the given capacity. Operations are ("put", key, value) or ("get", key): - get returns the value (or −1 if absent) and marks the key as most recently used. - put inserts or updates the key and marks it most recently used. When the size exceeds capacity, evict the least recently used key. Return the list of get results. Each operation must be O(1).
Signature
def lru_simulate(capacity: int, ops: list[tuple]) -> list: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> lru_simulate(2, [('put',1,1),('put',2,2),('get',1),('put',3,3),('get',2),('get',3),('get',1)]) == [1, -1, 3, 1]
True
>>> lru_simulate(1, [('put','a',1),('put','b',2),('get','a'),('get','b')]) == [-1, 2]
TrueHints
Hash map plus a doubly linked list (or OrderedDict move_to_end / popitem(last=False)).
get marks the key most recently used; put inserts/updates and refreshes recency; evict the least-recently-used on overflow.
Each operation is O(1).
Reference solution
from collections import OrderedDict
def lru_simulate(capacity, ops):
from collections import OrderedDict
c = OrderedDict(); out = []
for op in ops:
if op[0] == "get":
k = op[1]
if k in c:
c.move_to_end(k); out.append(c[k])
else:
out.append(-1)
else:
_, k, v = op
if k in c:
c.move_to_end(k)
c[k] = v
if len(c) > capacity:
c.popitem(last=False)
return outWhat a strong solution covers
- Hash map plus a doubly linked list (or
OrderedDict.move_to_end/popitem(last=False)). - Updates refresh recency.
- Discusses thread safety and TTL, and its use as a feature/embedding cache in serving.
Common mistakes
- forgetting to refresh recency on
getor on updatingput - O(n) eviction by scanning.