Sub topic 11
Evicting the least recently used entry at capacity
This chapter covers the eviction step inside put. It assumes you can read Python classes and dictionaries, know Big-O notation, and have followed the earlier chapters on the hash map, the doubly linked list with sentinel nodes, and the get and put operations.
When eviction happens
A cache has a fixed capacity. Eviction is the removal of one entry to make room for a new one. It triggers only when both conditions hold:
- The key being written is not already in the cache.
- The cache already holds
capacityentries.
Updating an existing key never evicts. It only replaces the value and promotes the node. This is why put checks the map before it checks the size.
The eviction step
The least recently used entry sits right before the tail sentinel. Removing it takes two actions, and both are required:
- Unlink the node from the list with
pop_back. - Delete its key from the dictionary.
The second action is why each node stores its own key. The list hands back only a node. Without node.key, you would have to scan the dictionary to find which entry pointed to that node, and that scan would cost O(n).
The code
This is the relevant part of put, shown with the full class so it runs as written.
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.value
def put(self, key, value):
node = self.map.get(key)
if node is not None:
node.value = value
self.order.move_to_front(node)
return
if len(self.map) >= self.capacity:
oldest = self.order.pop_back()
del self.map[oldest.key]
node = Node(key, value)
self.map[key] = node
self.order.add_front(node)The class relies on Node and DoublyLinkedList from the previous chapter. Eviction runs before the new node is added, so the cache never holds more than capacity entries, not even briefly.
Tracing an eviction
cache = LRUCache(2)
cache.put(1, "a")
cache.put(2, "b")
print(cache.get(1)) # a (key 1 is now most recent)
cache.put(3, "c") # evicts key 2
print(cache.get(2)) # None
print(cache.get(3)) # c
print(cache.get(1)) # aAfter the two put calls, the list runs from front to back as 2, 1. The get(1) call promotes key 1, so the order becomes 1, 2. Inserting key 3 finds the map full. pop_back returns the node for key 2, the code deletes key 2 from the map, and key 3 goes to the front. Key 2 was inserted later than key 1, but key 1 was read more recently, so key 2 is the one evicted.
Common mistakes
- Popping the node but forgetting
del self.map[oldest.key]. The map then keeps a reference to a node that is no longer in the list. A latergeton that key would move a detached node and corrupt the list. - Evicting before checking whether the key exists. An update to a key in a full cache would then drop an entry for no reason.
- Allowing capacity 0.
pop_backwould returnNoneon an empty list, andoldest.keywould raise anAttributeError. The constructor check prevents this.
Exercise
A cache with capacity 3 holds keys 1, 2, 3, and key 1 is the least recently used. You call put(3, "new"). Does any entry get evicted, and why?
Show answer
No. Key 3 already exists, so put takes the update path: it replaces the value and moves the node to the front. The size check is skipped, so nothing is evicted.
Exercise
Why does pop_back in the list return the node rather than just the key or nothing at all?
Show answer
The caller needs oldest.key to delete the matching dictionary entry in O(1). Returning the node gives access to that key without searching the map.