Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Problem
What is asked, and how to take it apart
The point: the problem is two verbs and one budget. get and put, both O(1), with room for a fixed number of entries.
What they say, and what they mean
The first minute
Interviewer
Design a cache with a fixed capacity that throws out the least recently used entry.
You
Two methods, then:
get(key)andput(key, value). Does reading count as using?Interviewer
Yes. Both reading and writing make a key the most recent.
You
What should a miss return, and is a put on a known key an update?
Interviewer
Choose something sensible for a miss. A put on a known key updates it.
You
Then a miss returns nothing, which is
Nonein Python and an empty optional elsewhere. For a version with positive integers only, minus one is the usual sign. I assume one thread at first and come back to it. Is O(1) expected for both?Interviewer
On average, yes.
From a vague sentence to code in five steps
- 1
The contract
Two methods, a capacity of at least one, what a miss looks like.
- 2
The forbidden loop
Say it: no walk over the entries in get or put. That excludes most first ideas.
- 3
Two questions, two structures
Where is it? A map. Who is last? A list.
- 4
Two small operations
Unlink and push to the front. Write them first and trust them afterwards.
- 5
One invariant
Map and list hold the same nodes. Check it aloud after each method.
C.I.M.P.L.: five places to look
Container, Item, Manager, Policy, Lifecycle. For a data structure problem, start at the container and the policy: they decide everything else.
| Letter | Question | Here | In code |
|---|---|---|---|
| Container | What holds the data? | A hash map and a doubly linked list over the same nodes | _nodes, _order |
| Item | What is stored? | A node: key, value, two neighbours | Node |
| Manager | Who runs it? | The cache. It is the only one that changes both structures | LruCache |
| Policy | What could vary? | Who goes first: LRU, LFU, FIFO. A method today, an interface when a second one is needed | last(), touch() |
| Lifecycle | Which states? | An entry: created, used, evicted. The cache: cold, warm, full | The place in the list |
Good first sentences
- "I need to find by key and to know who is last, both in O(1)."
- "One structure cannot do both, so one node lives in two."
- "I start with one thread and say where threads would hurt."
Sentences that cost you
- "I will use an ordered dictionary." And then?
- "A Singleton cache with a strategy factory."
- "I sort by time stamp when it is full."