Sub topic 12
Checking time and space complexity
This chapter assumes you have the LRUCache, Node, and DoublyLinkedList classes from the earlier chapters and know Big-O notation. Here you add up the cost of each step in get and put, then confirm the result by measuring.
Cost of each step
Every operation is a short chain of simple steps. None of them loops over the stored entries.
| Step | Used by | Cost |
|---|---|---|
| `self.map.get(key)` | `get`, `put` | O(1) average |
| `remove(node)` (two pointer writes) | `move_to_front` | O(1) |
| `add_front(node)` (four pointer writes) | `move_to_front`, `put` | O(1) |
| `pop_back()` | `put` at capacity | O(1) |
| `del self.map[oldest.key]` | `put` at capacity | O(1) average |
| `Node(key, value)` and `self.map[key] = node` | `put` for a new key | O(1) average |
A sum of a fixed number of O(1) steps is still O(1). So get and put are both O(1) on average, whether the cache holds 10 entries or 10 million.
Why "average"
The linked list work is exact O(1). The hash map work is O(1) only on average. If many keys collide in the same bucket, a lookup can degrade toward O(n). Python's dict makes this rare with a good hash function. A resize while the dictionary grows costs O(n) once, but that cost is spread over many inserts, so it is amortized O(1). Your cache never holds more than capacity entries, and the map stops growing once it fills.
Keys must be hashable. A key type with a slow __hash__ makes every operation slower, and this cost is outside the cache itself.
Space complexity
The cache stores at most capacity entries. Each entry has one Node and one dictionary slot that points to it. The two sentinels add two more nodes. Total space is O(capacity), or O(n) for n entries. It does not grow with the number of operations, because eviction removes the old node from both structures. The __slots__ declaration on Node does not change the Big-O. It does cut the memory used per node, because each node skips its own __dict__.
Measuring it
Big-O describes how cost grows, so a quick experiment should show roughly flat time per operation as capacity grows.
import time
def time_per_op(capacity, ops=200_000):
cache = LRUCache(capacity)
for i in range(capacity):
cache.put(i, i)
start = time.perf_counter()
for i in range(ops):
key = i % (capacity * 2) # about half the lookups miss
if cache.get(key) is None:
cache.put(key, i)
elapsed = time.perf_counter() - start
return elapsed / ops * 1e6
for cap in (1_000, 10_000, 100_000):
print(cap, round(time_per_op(cap), 2), "microseconds per op")Expect similar numbers for all three sizes. Larger caches may run a little slower because of CPU cache misses, but the time should not grow tenfold when capacity does.
Exercise
A teammate says get is O(n) because it calls move_to_front, which touches the list. What is wrong with that claim, and what is the space complexity of a cache with capacity k after one million operations?
Show answer
move_to_front is a remove plus an add_front, which together make a fixed number of pointer updates. It never walks the list, because the map returns the node directly. So get is O(1) on average. Space is O(k), since eviction keeps the number of nodes and map entries at or below k no matter how many operations ran.