6. LRU Cache (Hash Map + Doubly Linked List)
A fixed-size cache that evicts the least recently used key. A hash map gives O(1) lookup and a doubly linked list keeps keys in usage order, so get and put are both O(1).
How it works
An LRU (least recently used) cache needs two things at once: find a key fast, and know which key was touched longest ago. Neither structure alone does both, so combine them:
- a hash map from key to list node, for O(1) lookup;
- a doubly linked list ordered from least recently used (front) to most recently used (back), for O(1) moves and evictions.
Every get or put of an existing key unlinks its node and re-attaches it at the back. When a new key arrives and the cache is full, the node at the front is removed from both the list and the map. Two sentinel nodes (head and tail) remove all empty-list special cases.
Diagram
flowchart LR
M["hash map: key to node"] -.-> N1
M -.-> N2
H["head sentinel"] --> N1["key 3: least recent"]
N1 --> N2["key 4: most recent"]
N2 --> T["tail sentinel"]
T -->|"next put of a new key evicts"| N1
Step-by-step trace
Input: Capacity 2. put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4).
| Operation | Returns | Evicted | Keys (least -> most recent) |
|---|---|---|---|
| put(1, 1) | - | - | [1] |
| put(2, 2) | - | - | [1, 2] |
| get(1) | 1 | - | [2, 1] |
| put(3, 3) | - | 2 | [1, 3] |
| get(2) | -1 | - | [1, 3] |
| put(4, 4) | - | 1 | [3, 4] |
| get(1) | -1 | - | [3, 4] |
| get(3) | 3 | - | [4, 3] |
| get(4) | 4 | - | [3, 4] |
Result: The gets returned [1, -1, -1, 3, 4]. Key 2 was evicted because get(1) made key 1 more recent; later key 1 was evicted in turn.
Complexity
| Operation | Time | Space |
|---|---|---|
| get / put | O(1) | O(capacity) |
Python reference implementation
class _Node:
def __init__(self, key=None, value=None):
self.key, self.value = key, value
self.prev = self.next = None
class LRUCache:
"""Hash map + doubly linked list. Most recently used sits next to `tail`."""
def __init__(self, capacity):
self.capacity = capacity
self.map = {}
self.head, self.tail = _Node(), _Node() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _push_back(self, node): # mark as most recent
node.prev, node.next = self.tail.prev, self.tail
self.tail.prev.next = node
self.tail.prev = node
def get(self, key):
node = self.map.get(key)
if node is None:
return -1
self._unlink(node)
self._push_back(node)
return node.value
def put(self, key, value):
"""Insert or update; returns the evicted key or None."""
if key in self.map:
node = self.map[key]
node.value = value
self._unlink(node)
self._push_back(node)
return None
evicted = None
if len(self.map) == self.capacity:
lru = self.head.next # least recently used
self._unlink(lru)
del self.map[lru.key]
evicted = lru.key
node = _Node(key, value)
self.map[key] = node
self._push_back(node)
return evicted
def keys_lru_to_mru(self):
out, node = [], self.head.next
while node is not self.tail:
out.append(node.key)
node = node.next
return out
Common mistakes and tips
- Update recency on
gettoo, not only onput. - When updating an existing key, move it to the back; do not insert a second node.
- In Python,
collections.OrderedDictwithmove_to_endandpopitem(last=False)is a valid shortcut; interviewers often ask for the linked-list version anyway.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Hash Tables (Separate Chaining) | Next: Binary Trees and Traversals |