MediumCachingPython 3

LRU TTL Cache

Combine recency ordering and TTL cleanup without corrupting cache invariants.

35m3 sample tests5 hidden tests

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. For an existing live key, overwrite the value, move it to most recently used, and replace its TTL from now() (ttl=None means no expiry).
  • get(key) returns the value or None when missing or expired.
  • get marks a key as most recently used.
  • When capacity is exceeded, evict expired entries first, then least recently used entries. Cleanup of expired keys must happen on put when reclaiming capacity, independent of any earlier get for the expired key.
  • 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 None

Constraints

  • Use standard-library Python only.
  • Don't use functools.lru_cache.

Editor