Sub topic 10
Implementing put for new and existing keys
This chapter assumes you have the Node and DoublyLinkedList classes from the earlier chapters (sentinel head and tail, add_front, remove, move_to_front, pop_back). It also assumes you have a get that promotes the entry it reads. Here we write put.
Two cases, one rule
put(key, value) must handle two situations:
- The key already exists. Update the stored value and mark the entry as most recently used.
- The key is new. Create a node, register it in the dictionary, and place it at the front of the list.
In both cases the written entry ends up at the front. A write counts as a use, just as a read does.
The code
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)Walking through the branches
The first line, self.map.get(key), is an O(1) lookup that returns the node or None.
If the node exists, put changes node.value in place. It does not create a new node. The dictionary entry and the list position both stay valid, and move_to_front only relinks the neighbors. It then returns early so the new-key code never runs.
If the node is new, the capacity check comes before the insert. When the cache is full, pop_back removes the least recently used node, and del self.map[oldest.key] removes its dictionary entry. That deletion works only because each node stores its own key. Eviction is covered fully in the next chapter. Here it is enough to see where it sits in put.
Only then do we create the node, record it in self.map, and call add_front. Both structures are updated, so they stay in agreement.
Common errors
- Evicting when updating. If you check capacity before the existing-key branch, updating a key in a full cache evicts an entry for no reason. Always test for an existing key first.
- Forgetting
move_to_fronton update. The value changes, but the entry keeps its old rank and may be evicted too early. - Inserting before evicting. With capacity 1, adding the new node first lets
pop_backremove the node you just added. - Updating only one structure. A node in the list but not in the map is unreachable. A map entry whose node is not in the list is never evicted.
Checking the behavior
cache = LRUCache(2)
cache.put(1, "a")
cache.put(2, "b")
cache.put(1, "z") # update: key 1 becomes most recent, no eviction
cache.put(3, "c") # evicts key 2, not key 1
print(cache.get(1)) # z
print(cache.get(2)) # None
print(cache.get(3)) # cExercise
A cache with capacity 2 holds keys 1 and 2, and key 2 is the most recent. You call put(1, "new"). Which key is the least recently used afterward, and is anything evicted?
Show answer
Nothing is evicted, because key 1 already exists and the update path returns before the capacity check. Key 1 moves to the front, so key 2 becomes the least recently used.