Implement a thread-safe or TTL LRU cache
Implement get(key) and put(key, val) in O(1) average time with max capacity and optional TTL expiration.
Model Answer & Explanation
from collections import OrderedDict
import time
class TTLLRUCache:
def __init__(self, cap: int, ttl: float):
self.cap, self.ttl = cap, ttl
self.store = OrderedDict()
def get(self, key):
if key not in self.store:
return None
val, exp = self.store[key]
if time.monotonic() > exp:
del self.store[key]
return None
self.store.move_to_end(key)
return val
def put(self, key, val):
self.store[key] = (val, time.monotonic() + self.ttl)
self.store.move_to_end(key)
if len(self.store) > self.cap:
self.store.popitem(last=False) Python’s OrderedDict provides move_to_end(key) and popitem(last=False) in O(1), making LRU concise and clean. Store (value, expires_at) tuples to support TTL expiration lazily on get() and proactively on eviction. Wrap operations in threading.Lock if shared across threads.