A list keeps the order, but moving a key in it costs O(n)
list.remove and list.pop(0) both touch O(n) keys
The obvious version keeps the values in a dict and the order in a list, oldest first:
class SlowLRU: def __init__(self, capacity): self.capacity, self.data, self.order = capacity, {}, [] def get(self, key, default=None): if key not in self.data: return default # searches the list for key self.order.remove(key) self.order.append(key) return self.data[key] def put(self, key, value): if key in self.data: self.order.remove(key) elif len(self.data) >= self.capacity: # shifts every key behind it del self.data[self.order.pop(0)] self.data[key] = value self.order.append(key)
It passes the trace. The two marked lines are the problem:
Predict
The order list holds 100,000 keys. How many of them does order.pop(0) move?
Both calls touch the whole list
order.remove("c")
abcde
order.pop(0)
abcde
Red leaves the list. remove compares the blue keys on its way to c, and every orange key moves one place left.
Both are O(n): the work grows with the number of entries.
With 100 times the entries, the list's get took about 100 times longer
Fill a cache to its capacity n with the integer keys 0 to n - 1. Then time 2,000 gets of stored keys and 2,000 puts that each evict. On an M1 Pro laptop with Python 3.12, median of 5 runs, with this lesson's three ways to keep the order:
Keeps the order in
get, n = 1,000 → 100,000
evicting put, n = 1,000 → 100,000
a list
3.1 → 304 µs
0.25 → 16.1 µs
a doubly linked list
0.18 → 0.36 µs
0.40 → 0.40 µs
an OrderedDict
0.08 → 0.19 µs
0.15 → 0.16 µs
One get at n = 100,000
a list
304 µs
a doubly linked list
0.36 µs
an OrderedDict
0.19 µs
The two O(1) versions barely show next to the list.
At 100,000 entries the list's get takes roughly a thousand times as long as the other two. Their times about doubled while the list's grew a hundred times: that near-flat line is what O(1) looks like.
Pick an answer above to see the rest
Predict
At n = 100,000 the list's get took 304 µs, but its evicting put only 16.1 µs. Both shift keys. What makes get slower?
The list lacks two things. It can't go from a key straight to its place in the order. And it can't take a key out of the middle without shifting the rest. A doubly linked list fixes the second. Point the dict at the list's nodes, and that fixes the first.
In the editor, count both costs on the five keys of the figure. remove_touches(order, key) and pop_front_touches(order) each return a pair: how many keys the call passes on its way, and how many shift one place left after it.
Pick an answer above to see the rest
Instructions
1
Write remove_touches(order, key): how many keys order.remove(key) passes on its way to key, and how many keys behind key then shift one place left.
2
Write pop_front_touches(order): the same pair for order.pop(0).