Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Requirements
Sentences that become methods
The point: each requirement should be visible in one place of the code. If you cannot point at it, it is not met.
What it must do
| Requirement | Detail | Where |
|---|---|---|
| Create | Fixed capacity, at least 1. Anything else is an error at once | __init__ |
| Get | The value, or nothing. A hit makes the key the most recent | get |
| Put, new key | Stores the pair at the front. If full, the least recent goes first | put, _evict |
| Put, known key | New value, most recent, nobody is evicted | put, first branch |
| Evict | From both structures, and tell the caller who went | _evict |
| Remove | Optional: forget one key. Needed for expiry and invalidation | remove |
| Peek | Optional: look without changing the order | peek |
How well it must do it
| Quality | Target | How you would show it |
|---|---|---|
| Time | O(1) on average for get and put | No loop in either of them |
| Memory | O(capacity), never above, not even for a moment | Evict before insert |
| No leaks | A removed node is reachable from nowhere | Map entry gone, pointers cleared |
| Threads | Optional. If asked, each method is one step | One lock, then measure |
| Clarity | Pointers in one class | RecencyList can be tested alone |
Eight questions, and a default if nobody answers
| Question | Default | What another answer changes |
|---|---|---|
| What does a miss return? | Nothing, or a default the caller passes | -1 is fine if values are never negative |
| Which types? | Any key that can be hashed | Integers only: an array could replace the map |
| Can a value be None? | Not distinguished from a miss | Return an optional, or a private sentinel object |
| Does writing count as using? | Yes | No: a put on a known key would not touch |
| Does reading count as using? | Yes, that is LRU | No: it becomes FIFO |
| Threads? | One | A lock, see the FAANG pages |
| Do entries get old? | No | A deadline for each entry |
| Are entries of similar size? | Yes, so we count entries | Weights, and an eviction that may take several |
From C.I.M.P.L. to requirements
Container
O(1) lookup, O(1) reordering, a size that is always known.
Item
Key, value, both neighbours. The key is there for the eviction.
Manager
get and put in O(1), and three small helpers: push, unlink, touch.
Policy
Remove the last one. Must be replaceable, need not be pluggable.
Lifecycle
Entry: created, used, evicted. Cache: empty, warm, full. After full it stays full until something is removed.