Sub topic 4
The hash map: fast lookup, no order
This chapter assumes you know basic Python classes and dictionaries and can read Big-O notation. It looks at what a hash map gives an LRU cache and what it can't.
What the hash map gives you
A Python dict is a hash map. It turns a key into a number (the hash), uses that number to jump to a slot, and returns the stored value. Lookup, insert, and delete all take O(1) time on average. That matches the cache's need to answer get(key) without searching.
What it does not give you
A hash map answers "is this key here, and what is its value?" It does not answer "which key was used least recently?"
Since Python 3.7, a dict remembers the order in which keys were first inserted. That is not recency order. Reading a key does not move it, and Python has no operation that moves a key to the end in O(1). You can delete a key and insert it again, which puts it last. But the dictionary's internal storage then keeps gaps from deleted entries. Repeatedly asking for the oldest key can become slow, and the behavior depends on how CPython implements dict. This design should not rely on that.
The naive version: a dict only
Suppose we track recency by storing a counter with each value. Each access writes the current counter value next to the entry.
class DictOnlyCache:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.data = {} # key -> (value, last_used)
self.clock = 0
def _tick(self):
self.clock += 1
return self.clock
def get(self, key):
entry = self.data.get(key)
if entry is None:
return None
self.data[key] = (entry[0], self._tick())
return entry[0]
def put(self, key, value):
if key not in self.data and len(self.data) >= self.capacity:
oldest = min(self.data, key=lambda k: self.data[k][1])
del self.data[oldest]
self.data[key] = (value, self._tick())
cache = DictOnlyCache(2)
cache.put(1, "a")
cache.put(2, "b")
cache.get(1)
cache.put(3, "c")
print(cache.get(2)) # None, key 2 was evicted
print(cache.get(1)) # aThis is correct. get is O(1). But put on a full cache calls min over every entry to find the oldest one, which is O(n). With a cache of a million entries, every insertion that causes an eviction scans a million entries.
The takeaway
- The hash map gives O(1) lookup, insert, and delete by key.
- It has no cheap way to find or reorder by recency.
- Storing timestamps moves the cost to eviction, where finding the minimum is O(n).
The cache needs a second structure that keeps keys in recency order and can move one key to the front in O(1). That is the job of the doubly linked list in the next chapter.
Exercise
In DictOnlyCache, which operation is O(n), and why does a plain dict make it hard to improve?
Show answer
put is O(n) when the cache is full, because min scans every entry to find the smallest last_used value. A dict is indexed by key, not by recency, so it has no way to return the least recently used key directly. Reading a key also does not change its position in the dict.