Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
How to approach it
What this question tests, where it gets hard, and how to spend the time.
What this problem tests
Choosing structures
From the operations to the structures, aloud, and not from memory.
Pointer care
Four writes in the right order. Draw them.
An invariant
Two structures, one truth.
Concurrency sense
Seeing that a read writes.
Change
Time, weight and policy as layers.
Spend the 45 minutes
| Minutes | Do | Have at the end |
|---|---|---|
| 0 to 4 | Contract and questions | get, put, a miss, capacity |
| 4 to 9 | Reject slow ideas, choose two structures | A drawing of head, nodes, tail and the map |
| 9 to 24 | Code: node, list, get, put | Something that runs |
| 24 to 29 | Trace: hit, update when full, eviction, capacity 1 | A bug found by yourself, or none |
| 29 to 41 | Threads, then one extension | One lock, its price, one layer |
| 41 to 45 | Tests and what you would do next | The invariant as a test |
If you are stuck
H, D, L
Hash map to find. Doubly linked so that a node can leave from the middle. List with the most recent at the head and the least recent at the tail. Three letters, and each has a reason you can give.
Sounds like this
- "Two questions, two structures."
- "I write unlink and push once."
- "Known before full."
Not like this
- "I remember this one."
- Five null checks in unlink
- A lock before the code works