LRU cache with TTL
An LRU cache where entries also expire after ttl_s, with O(1) get and set and an injected clock so it is testable.
Statement
Implement TTLCache(capacity, ttl_s, clock) with get(key) and set(key, value). Eviction is least-recently-used when over capacity. Any entry older than ttl_s is treated as missing. Both operations must be O(1).
clock is injected (returns seconds as a float) so tests can control time. Expired entries may be removed lazily.
Examples
capacity = 2, ttl_s = 10
t=0 set("a", 1); set("b", 2)
t=1 get("a") → 1 # a is now most recent
t=2 set("c", 3) # evicts b (LRU)
t=3 get("b") → None
t=11 get("a") → None # expired (set at t=0)Constraints
capacity ≥ 1. Up to 10⁶ operations. Discuss how you would bound memory from expired-but-never-read entries.
Open to everyone until Pro goes on sale · sign in to save your attemptSolve it in the editor with visible tests
Open in the app