Cache with TTL
medium · LRU eviction + time-based expiry
Brief-reported interview attribution (unverified): Amazon ("LRU Cache with a time constraint"), Microsoft
How to approach an LLD roundDesign a cache with a fixed capacity. Every entry may carry a TTL
in seconds (None = never expires). get returns None for a missing or expired
key and refreshes the recency of a live key (LRU). put on an existing key
updates its value and TTL and refreshes its recency. When the cache is full, insert
evicts the least recently used entry — but an expired entry is evicted first and
does not force a live entry out. Time comes from a clock callable passed to the
constructor (default: time.time).
class TTLCache:
def __init__(self, capacity, clock=None):
def get(self, key):
# -> value, or None if missing or expired
def put(self, key, value, ttl_seconds=None):
# insert or update; ttl_seconds=None means the entry never expires
Rules. Expiry is checked as now >= inserted_at + ttl_seconds. Expired
entries are removed lazily (on access, and before eviction). put with a TTL
starts the TTL at the time of the put.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
now = [1000.0]
c = TTLCache(2, clock=lambda: now[0])
c.put('a', 1, ttl_seconds=10)
now[0] = 1009.0
print(c.get('a'))
now[0] = 1010.0
print(c.get('a'))Starter code
class TTLCache:
def __init__(self, capacity, clock=None):
"""Initialize the state described in the problem."""
pass
def get(self, key):
"""-> value, or None if missing or expired"""
pass
def put(self, key, value, ttl_seconds=None):
"""insert or update; ttl_seconds=None means the entry never expires"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler