MediumCachingPython 3
LRU TTL Cache
Combine recency ordering and TTL cleanup without corrupting cache invariants.
35m1 sample tests1 hidden tests
LRU TTL Cache
Implement a bounded cache with least-recently-used eviction and optional TTLs.
Requirements
- Define
LRUTTLCache(capacity, now). put(key, value, ttl=None)stores a value.get(key)returns the value orNonewhen missing or expired.getmarks a key as most recently used.- When capacity is exceeded, evict expired entries first, then least recently used entries.
- Expiry is inclusive: a key is expired when
now() >= expires_at.
Example
python
1cache = LRUTTLCache(capacity=2, now=lambda: 0)
2cache.put("a", 1)
3cache.put("b", 2)
4assert cache.get("a") == 1
5cache.put("c", 3)
6assert cache.get("b") is NoneConstraints
- Use standard-library Python only.
- Do not use
functools.lru_cache.
Editor
1 2 3 4 5 6 7 8 9
Sample Tests
evicts least recently used entry
from solution import LRUTTLCache
cache = LRUTTLCache(capacity=2, now=lambda: 0.0)
cache.put("a", 1)
cache.put("b", 2)
assert cache.get("a") == 1
cache.put("c", 3)
assert cache.get("b") is None
assert cache.get("a") == 1
assert cache.get("c") == 3Results
Run sample tests or submit all tests.