Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Verify
Trace it with real values
The point: do not say done. Put eight calls through a cache for three and write the order after each.
Eight calls
Capacity 3
| Call | Branch | Order, front first | Map | Answer |
|---|---|---|---|---|
| put(1, 100) | new | 1 | 1 | nobody evicted |
| put(2, 200) | new | 2 1 | 1 2 | nobody evicted |
| put(3, 300) | new | 3 2 1 | 1 2 3 | nobody evicted |
| get(1) | hit | 1 3 2 | 1 2 3 | 100 |
| put(4, 400) | full, new | 4 1 3 | 1 3 4 | evicted (2, 200) |
| get(2) | miss | 4 1 3 | 1 3 4 | nothing |
| put(3, 999) | known | 3 4 1 | 1 3 4 | nobody evicted |
| put(5, 500) | full, new | 5 3 4 | 3 4 5 | evicted (1, 100) |
Python
from collections import OrderedDictclass Model: """The same rules with a dictionary that remembers its order. Last is most recent.""" def __init__(self, capacity): self.capacity, self.data = capacity, OrderedDict() def get(self, key): if key not in self.data: return None self.data.move_to_end(key) return self.data[key] def put(self, key, value): if key in self.data: self.data.move_to_end(key) elif len(self.data) == self.capacity: self.data.popitem(last=False) self.data[key] = valuem = Model(3)for step in ["put 1 100", "put 2 200", "put 3 300", "get 1", "put 4 400", "get 2", "put 3 999", "put 5 500"]: name, key, *rest = step.split() out = m.put(key, rest[0]) if name == "put" else m.get(key) print(f"{step:10} order {list(reversed(m.data))} answer {out}")Small inputs that break large designs
| Input | Must happen | What it finds |
|---|---|---|
| Capacity 1: put a, put b, get a | b in, a out, a miss | Lists that cannot have one node |
| Capacity 1: put a, put a again | Same node, new value | Full asked before known |
| get on an empty cache | A miss | Touching nothing |
| get of the node that is first already | No change | A node linked to itself |
| put of the key that is last, when full | Moved, nobody evicted | Evicting the node you are updating |
| Capacity 0 | An error when created | Evicting a sentinel |
| remove, then put of another key | Room was made, nobody evicted | Sizes that are counted by hand |
Four sentences that are true after every call
- 1
Same nodes
Each map value is in the list, each node of the list is in the map under its own key.
- 2
Within the limit
The size is at most the capacity.
- 3
Neighbours agree
For each node,
node.next.previs the node, and so isnode.prev.next. - 4
Front means last used
The key of the last successful get or put is at the front.
The question to ask at each line of put