Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Grow the design
Start with the smallest system that works. Change it only when something breaks.
Four steps, each forced by a sentence
| Sentence | Forces | Price |
|---|---|---|
| "get in O(1)" | A map from key to node | Memory for the table |
| "the least recent goes, O(1)" | A list in order of use | Two links for each entry |
| "a hit moves from the middle" | Doubly linked, with sentinels | Four writes to push, two to unlink |
| "the evicted key leaves the map" | The key in the node | One reference |
What is inside the lock, and what is not
The class diagram is on the UML page of the solution. Draw three boxes: cache, list, node.