6/37
Part 2 of 6 · The LRU orderLearn and do

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?

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?

Pick an answer above to see the rest