Design an LRU cache
medium 85 minDesign 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
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?
Interviewer
Start with the structure, then threads.
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.
Interviewer
Should it survive a restart?
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 say | Then |
|---|---|
| Threads from the start | One lock layer, written last and mentioned first |
| Values may be null | Optional, or a private marker |
| Sizes differ | Weights, while and not if |
| Entries get old | Expiring layer, clock as a parameter |
| Strict order is required | No shards, no buffers |
In
- get, put, capacity
- O(1) on average
- The invariant
Out, unless asked
- Persistence
- Distribution
- Builders and listeners