AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Watch lesson4:49

Agree on the scope

Ask what changes the design, then commit to a short list.

The scope in one minute

Cutting it down

  1. You

    I see four possible sizes of this problem: the plain structure, the same for many threads, a library with expiry and loading, and a cache server. Which one?

  2. Interviewer

    Start with the structure, then threads.

  3. You

    Good. One process, any key type, a limit on the number of entries. Reading and writing both count as use. No expiry until you ask. A miss returns a default.

  4. Interviewer

    Should it survive a restart?

  5. You

    I would say no: the truth is in the store behind it, and a cold start is slow but correct. I design get and put first.

What each answer decides

If they sayThen
Threads from the startOne lock layer, written last and mentioned first
Values may be nullOptional, or a private marker
Sizes differWeights, while and not if
Entries get oldExpiring layer, clock as a parameter
Strict order is requiredNo shards, no buffers

In

  • get, put, capacity
  • O(1) on average
  • The invariant

Out, unless asked

  • Persistence
  • Distribution
  • Builders and listeners