Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
A map finds the node, a list remembers the order. Watch both change in every call.
Operations
Fill it, then evict
Four puts into a cache for three. The fourth one pays with the node at the back.
Step 1 of 7
Empty
A map without keys, and a list with two sentinels and nothing between them.
Step 1: Empty
def put(self, key, value): node = self._nodes.get(key) if node is not None: node.value = value self._order.touch(node) return None evicted = None if len(self._nodes) == self.capacity: evicted = self._evict() node = Node(key, value) self._nodes[key] = node self._order.push_front(node) return evicted- Cost
- O(1)
- Guarantee
- Never above 3
- Array, 3 entries
- 3 looks
- Array, 1,000,000
- 1,000,000 looks
Evict first, insert second: the limit is never broken, not even for a moment.
In the real world
The same lru cache doing real jobs. Pick one and step through it.
A report reads a million rows once. What is left of the hot entries?
Step 1 of 4
Warm
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| plain | A | B | C | D |
| split | A protected | B protected | C trial | D trial |
Both caches hold the hot keys A, B, C, D. The second one is split: two protected places, two on trial.
Step 1: Warm
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading without moving
criticalThe order becomes the order of writing. That is FIFO, and it throws out the most popular key.
Wrongdef get(self, key): return self._nodes[key].valueRightnode = self._nodes.get(key)if node is None: return defaultself._order.touch(node)return node.valueEvicting from one structure only
criticalThe map grows for ever and leads to nodes that are in no list.
Wrongself._order.unlink(node)Rightself._order.unlink(node)del self._nodes[node.key]Asking full before known
criticalAn update of a full cache evicts an entry that was not in the way.
Wrongif len(self._nodes) == self.capacity: self._evict()node = self._nodes.get(key)Rightnode = self._nodes.get(key)if node is not None: ... # update and returnif len(self._nodes) == self.capacity: self._evict()Two writes in the wrong order
majorAfter the first line head.next is the node itself. It now points at itself, and every walk hangs.
Wrongself._head.next = nodeself._head.next.prev = nodeRightself._head.next.prev = nodeself._head.next = nodeUpgrading a read lock
criticalIn Java a thread that holds the read lock and asks for the write lock waits for itself, for ever.
WrongreadLock.lock();...writeLock.lock(); // never returnsRightlock.lock(); // one lock, get and putLoading under the lock
majorOne slow database call stops every hit of every other key.
Wrongwith self._lock: value = self._load(key)Right# note the load under the lock, do it outside,# let the others wait for that one result
Interview tips
Open with
- Map: find the node.
- List: know the order.
- Node: knows its key.
Draw
- head, two nodes, tail.
- The four writes.
- The map pointing at nodes.
Prove it
- Trace capacity 1.
- Trace an update when full.
- Map size = list length.
Never
- A search in get.
- A read lock around get.
- A load under the lock.