Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
API and data
The contract first, then the data that serves it.
The public surface
| Call | Returns | Changes the order? | Notes |
|---|---|---|---|
LruCache(capacity) | A cache | Error below 1 | |
get(key, default) | The value, or the default | Yes, on a hit | Never loads |
put(key, value) | The pair that had to go, or nothing | Yes | Never evicts on an update |
peek(key) | The value, or nothing | No | For layers and tests |
remove(key) | Was it there? | No, the others keep theirs | Twice is fine |
len(cache) | Number of entries | No | O(1) |
Why it looks like this
- 1
No nodes outside
A caller with a node could keep one that is gone.
- 2
No
containsKeybefore getTwo calls with a gap. One get with a default says the same.
- 3
put tells who went
Layers can react without a listener inside the core.
- 4
No
setCapacityIf asked: shrink by evicting in a loop, grow by changing one number.
Should put return something?
BreaksThe old value of the key, mixed with the evicted one
- How
- Whatever left.
- Limit
- The caller cannot tell an update from an eviction.
- Choose when
- Never.
WorksNothing
- How
- As in the puzzle.
- Limit
- Evicted values that need closing are lost.
- Choose when
- Plain data.
StrongThe evicted pair, or nothing
- How
- One optional pair.
- Limit
- Most callers ignore it.
- Choose when
- A core that layers build on.