Sub topic 6
Joining the two: map from key to list node
This chapter assumes you know Python classes and dictionaries, Big-O notation, and that Python variables hold references to objects. It also assumes you have seen the hash map and doubly linked list from the previous two chapters.
The problem each structure leaves open
A dictionary finds a value by key in O(1) average time, but it has no usable notion of "least recently used". A doubly linked list can move a node to the front or remove it in O(1) once you hold the node. To find a node by key, though, you have to walk the list, which is O(n).
Each structure supplies what the other lacks. The dictionary gives fast lookup. The list gives cheap reordering.
The core idea: share node references
Store the list nodes themselves as the dictionary's values. The dictionary maps key -> Node, and the list links those same Node objects in recency order. No copies are made. Both structures point at one object.
Here node 3 is the most recent and node 2 is the least recent. A lookup of key 1 uses the map to jump straight to node 1. Because node 1 holds prev and next, the list can unlink it and reinsert it after head without touching any other node.
A minimal demonstration
This snippet builds the shared structure by hand for two keys. It uses a bare Node class and no sentinels, so you can see the sharing on its own.
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
a = Node(1, "a")
b = Node(2, "b")
a.next, b.prev = b, a # list order: a <-> b
table = {1: a, 2: b} # the map stores the same objects
print(table[2] is b) # True: one object, two ways to reach it
print(table[2].prev.key) # 1: from a key, we can step along the listtable[2] costs O(1). From there, prev and next give the neighbors without any search. That is the whole trick.
What each structure is responsible for
| Question | Answered by | Cost |
|---|---|---|
| Is this key cached, and where is its node? | Dictionary | O(1) average |
| Which entry is least recently used? | Node just before the tail | O(1) |
| Move this entry to "most recent" | Linked list, given the node | O(1) |
| Delete the evicted entry from the map | Dictionary, using the key stored in the node | O(1) average |
Why each node stores its key
The last row explains a detail in the code. When the list gives you the oldest node, you must also delete its entry from the dictionary. The list only knows nodes, so the node has to carry its own key. Without it, you would have to scan the dictionary to find which key points at that node.
Keeping the two in sync
The design has one invariant. Every key in the dictionary has exactly one node in the list, and every node in the list has exactly one key in the dictionary. Each operation must change both structures together. Common bugs break this rule in one of two ways:
- Adding a node to the list but forgetting
self.map[key] = node. - Popping the oldest node but forgetting
del self.map[oldest.key].
Either bug leaves a stale entry, and the cache then returns wrong results or exceeds its capacity.
Exercise
Why can't the dictionary store only values, with the linked list storing keys? What goes wrong on eviction or promotion?
Show answer
Without a reference to the node, promoting a key would require searching the list for it, which is O(n). Storing the node in the dictionary gives O(1) access to the node. Eviction also needs the key stored in the node, so the matching dictionary entry can be deleted in O(1).