KatInterview

Build an Expiring LRU Cache with an Injectable Clock

Data Structure DesignModel answer
MediumModel answerData Structure Designlru-cacheordereddictttl

Last updated

Design a fixed-capacity cache with least-recently-used eviction and per-entry expiry, and justify your data structures, tests and complexity.

Expiring LRU Cache

You are asked to design and implement a small in-memory cache in Python. Walk through your approach before coding, explain why you chose your data structures, and finish with unit tests and a complexity analysis.

Required behavior

  • The cache is created with a fixed capacity, and optionally a default lifetime for entries.
  • put(key, value, ttl=None) stores a value that becomes invalid ttl seconds after it was written. If ttl is omitted, the cache default applies. If neither is set, the entry never expires.
  • get(key, default=None) returns the stored value, or default if the key is absent or its entry has expired.
  • When an insert would push the cache over capacity, the least recently used entry is evicted.
  • Both get and put count as a "use" and refresh an entry's recency.
  • Overwriting an existing key replaces the value and restarts its lifetime.
  • A non-positive capacity or a negative TTL must raise ValueError.
  • Target scale is up to about 100,000 entries, so every operation should be O(1) on average.

What to deliver

  1. A short statement of the questions you would clarify and your assumptions.
  2. The design: data structures and the trade-offs behind them.
  3. Clean, modular Python with type hints. Time must be injectable so tests do not need sleep.
  4. Unit tests covering normal use and edge cases, plus a short sample run.
  5. Time and space complexity for each operation.
  6. A brief discussion of how the design would change for thread safety and for eager (proactive) expiry.

Hints

Hint 1

Which structure gives you O(1) lookup and also O(1) 'move to most-recent' and 'remove oldest'? Think about what Python's collections module offers.

Hint 2

Store an absolute expiry timestamp next to each value instead of a remaining duration, and only check it when the key is accessed. Pass the clock in as a parameter so tests can control time.

Hint 3

Decide what happens at the exact expiry instant, whether an expired entry still occupies a slot, and whether overwriting resets recency and lifetime. Write tests for each of those cases.