LRU Cache
LRU Cache is LeetCode 146 (Medium). Design a cache with a fixed capacity that throws out the least recently used key when it runs out of room. Implement the class LRUCache:
LRUCache(capacity)creates an empty cache that can holdcapacitykeys.get(key)returns the value stored forkey, or-1if the key is not in the cache. A successfulgetcounts as a use.put(key, value)stores the pair. If the key already exists its value is replaced, and that also counts as a use. If adding a new key pushes the size pastcapacity, the key that was used longest ago is removed.
Both get and put must run in O(1) average time. There are up to 2 × 10⁵ calls and the capacity can be 3000, so anything that scans the cache per call is too slow.
- 1 <= capacity <= 3000
- 0 <= key <= 10⁴
- 0 <= value <= 10⁵
- At most 2 * 10⁵ calls will be made to get and put.
Intuition
An lru cache has to answer two questions on every call, and each one needs a different structure:
- Is this key here, and where? A hash map answers that in O(1), but a hash map has no idea which key was used last.
- Which key is the oldest, and how do I mark this one as newest? A list kept in recency order answers that, but finding a key inside a list is O(n).
So keep both and let them point at the same objects. The list is a doubly linked list ordered from most recent (front) to least recent (back). The map stores key → node, not key → value. A lookup lands directly on the node; because the node knows both neighbours, it can be cut out and re-inserted at the front with four pointer writes. The node to evict is always the one at the back.
The list must be doubly linked: removing a node means rewiring the node before it, and only a prev pointer reaches that node without a scan.
Whenever you are asked for least-recently-used eviction, or any "O(1) lookup plus O(1) reorder" structure, the answer is a hash map whose values are nodes of a linked list. The same pairing appears in LFU cache (one list per frequency), in an ordered set with insertion order, and in Python's OrderedDict itself.
Approach
Before reading on, decide what the hash map's values should be, and write the exact pointer changes that move a node from the middle of a doubly linked list to its front. Then say why a singly linked list would not be enough.
The node and the two sentinels
Each node holds key, val, prev and next. The node stores its key so that, when it is evicted from the back of the list, the code knows which map entry to delete.
Create two dummy nodes, head and tail, linked to each other. Real nodes always sit between them, so every real node has a real neighbour on both sides: no None checks, and the empty cache is not a special case.
Two helpers do all the pointer work
remove(node):node.prev.next = node.nextandnode.next.prev = node.prev. The node is now out of the list.add_front(node): place it betweenheadandhead.next, fixing four pointers.
Every operation below is a combination of these two.
get(key)
- Key not in the map: return
-1. - Otherwise take the node from the map,
removeit andadd_frontit, because reading counts as a use. Return its value.
put(key, value)
- If the key exists,
removeits old node first. - Create a new node, store it in the map and
add_frontit. - If the map now holds more than
capacitykeys, the least recently used node istail.prev.removeit and delete its key from the map.
Why this solution is O(1)
The map lookup is O(1) on average. remove and add_front change a fixed number of pointers and never walk the list, because the map hands over the node and the node carries its own prev. The list is always in recency order: each use moves exactly the used node to the front, so the back is the key whose last use is oldest.
Code in Python, C++ and Java
map[1] at it, and link it in after head as the most recent key.map[2] at it, and link it in after head as the most recent key.remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 2 is now the least recent. Return 1.map[3] at it, and link it in after head as the most recent key. The cache now holds 3 keys, one more than it may, so the least recent key must go.map[2]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.map[4] at it, and link it in after head as the most recent key. The cache now holds 3 keys, one more than it may, so the least recent key must go.map[1]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 4 is now the least recent. Return 3.remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 3 is now the least recent. Return 4.get and put are O(1).map[1] at it, and link it in after head as the most recent key.map[2] at it, and link it in after head as the most recent key.map[3] at it, and link it in after head as the most recent key. The cache now holds 3 keys, one more than it may, so the least recent key must go.map[2]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 3 is now the least recent. Return 10.get and put are O(1).map[1] at it, and link it in after head as the most recent key.map[2] at it, and link it in after head as the most recent key. The cache now holds 2 keys, one more than it may, so the least recent key must go.map[1]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.get and put are O(1).Common pitfalls
Mapping key to value instead of key to node
self.map[key] = value self.order.remove(key) # list scan self.order.append(key)
self.map[key] = node self._remove(node) self._add_front(node)
With only the value in the map, marking a key as used means finding it in the order list first, which is O(n) per call and times out at 2 × 10⁵ calls.
Forgetting that get is a use
def get(self, key):
return self.map[key].val if key in self.map else -1node = self.map[key] self._remove(node) self._add_front(node) return node.val
Without the move, a key read a moment ago stays at the back and is the next one evicted. In the LeetCode example, get(1) must save key 1 so that put(3, 3) evicts key 2 instead.
Not storing the key inside the node
lru = self.tail.prev self._remove(lru) # which map entry is this?
lru = self.tail.prev self._remove(lru) del self.map[lru.key]
Eviction starts from the list, not from the map. If the node does not carry its key, there is no O(1) way to delete the matching map entry, and the map keeps a stale pointer that get would later return.
Evicting before inserting on an update
if len(self.map) == self.cap:
evict()
self.map[key] = nodeinsert first, then
if len(self.map) > self.cap:
evict()Updating a key that is already present does not grow the cache. Evicting when the size equals capacity throws out an innocent key on every update. Checking > after inserting handles new keys and updates with the same line.
Edge cases
Every put of a new key evicts the only other key. With the sentinels, the node at tail.prev is the old key right after the new one is added at the front, so no special case is needed.
The old node is removed before the new one is added, so the size does not change and nothing is evicted. The key moves to the front because an update counts as a use.
The node is removed and re-added in the same place. Harmless, and cheaper than a branch that checks for it.
Complexity
LRU Cache FAQ
How do you implement an LRU cache in O(1)?
- Structures: a hash map from key to node, and a doubly linked list with dummy head and tail, most recent at the front.
- get: missing key returns
-1; otherwise move the node to the front and return its value. - put: remove the old node if the key exists, add a new node at the front, and if the size exceeds capacity remove
tail.prevand its key from the map. - Complexity: O(1) per operation, O(capacity) space.
Can I use OrderedDict in Python?
Yes. OrderedDict is itself a hash map plus a doubly linked list. move_to_end(key) marks a use and popitem(last=False) removes the oldest key. It is accepted on LeetCode, but interviewers who ask you to build it expect the hand-built version above. functools.lru_cache is a decorator that memoises function calls; it is not a class you can call get and put on.
How do you build one in Java with LinkedHashMap?
Construct it with access order on: new LinkedHashMap<>(16, 0.75f, true), then override removeEldestEntry to return size() > capacity. get and put reorder the entries automatically and the eldest is dropped after each insert. Like OrderedDict, it hides the mechanism the question is testing.
Why does it need a doubly linked list?
Removing a node from the middle of a list means changing the next pointer of the node before it. A singly linked list can only reach that node by walking from the head, which is O(n). With a prev pointer it is one step away.
What are dummy head and tail nodes for?
They guarantee every real node has a node on both sides. Without them, removing the first or last node, or inserting into an empty list, each need their own None checks, and those branches are where most LRU cache bugs come from.