Sub topic 9
Implementing get and promoting the entry
This chapter assumes you have the Node and DoublyLinkedList classes from the previous chapter in the same file. It also assumes you are comfortable with Python dictionaries and with O(1) versus O(n) costs.
What get must do
An LRU cache orders entries by how recently they were used. A read counts as a use, so get has two jobs:
- Return the value for a key, or
Noneif the key is absent. - Move the entry to the "most recent" end of the order.
The second job is the one people forget. If get only returned the value, a frequently read key would still drift toward the tail and be evicted.
The two lookups are different
The hash map answers "is this key here, and where is its node?" in O(1). The list answers "which entry is oldest?" without searching. get uses both. It asks the map for the node, then asks the list to move that node.
The code
Because the map stores the node itself, move_to_front needs no search. It unlinks the node from its current neighbors and relinks it right after the head sentinel. Both steps are a fixed number of pointer updates.
class LRUCache:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.map = {} # key -> Node
self.order = DoublyLinkedList()
def get(self, key):
node = self.map.get(key)
if node is None:
return None
self.order.move_to_front(node)
return node.valueUsing self.map.get(key) performs one lookup. Writing if key in self.map and then self.map[key] would hash the key twice.
Trying it before put exists
put comes in the next chapter. To test get now, you can insert entries by hand:
cache = LRUCache(3)
for k, v in [(1, "a"), (2, "b"), (3, "c")]:
node = Node(k, v)
cache.map[k] = node
cache.order.add_front(node)
print(cache.get(1)) # a
print(cache.get(9)) # None
print(cache.order.tail.prev.key) # 2Key 3 was added last, so the list started as 3, 2, 1 from front to back. After get(1) it is 1, 3, 2. The node before the tail is now key 2, which is the next eviction candidate.
Common errors
- Forgetting to promote. The cache still returns correct values, so tests that only check values pass. Only eviction tests expose the bug.
- Promoting on a miss. A missing key has no node, so there is nothing to move. Return before touching the list.
- Returning a falsy value as a miss. If you write
if not node, a node is still truthy, so this works. But checkingif not valuewould wrongly treat stored values like0or""as misses. Compare the node withNone. - Ambiguous
None. If callers may storeNoneas a value, they cannot tell a hit from a miss. A sentinel default argument fixes this, and you can add one later if you need it.
Exercise
A cache of capacity 3 holds keys 1, 2, 3, with 3 most recent. You call get(1), then get(2). Which key is now next in line for eviction?
Show answer
Key 3. After get(1) the order is 1, 3, 2 (front to back). After get(2) it is 2, 1, 3. Key 3 is last, just before the tail sentinel, so it is the least recently used.