Python 3D Academyবাংলা

LRU cache: a dict plus a linked list

🌍 In real life. A small hostel fridge holds only two boxes. Whenever someone takes a box out and puts it back, it goes to the front. When a new box arrives and the fridge is full, the box nobody has touched for the longest time goes out to make room. A web browser keeps recently visited pages the same way, so the pages you use often load quickly.

The idea in one sentence: an LRU cache (least recently used) keeps at most capacity items, moves an item to the front every time it is read or written, and when it overflows throws out the item at the back, the one used longest ago.

Its words:

  • cache: a small, fast store of answers you may need again
  • capacity: how many items it may hold
  • hit / miss: the key is there (a hit) or not (a miss, which returns −1)
  • evict: throw an item out to make room

Step by step:

  1. get(key): if the key is missing, return −1; otherwise move it to the front and return its value
  2. put(key, value): store the value and move the key to the front
  3. if there are now more than capacity keys, remove the one at the back

Watch a cache of capacity 2. The left end is the most recently used:

Why a dict alone or a list alone is too slow. A dict finds a key in O(1) but has no idea which key is the oldest; finding it means looking at every key. A list kept in use order knows the oldest (the last item), but moving a key to the front means finding it and shifting everything: O(n). With 100,000 items and 1,000,000 requests, that is up to 100,000,000,000 steps.

The design: both together. Keep the items in a doubly linked list (Chapter 41), newest next to head and oldest next to tail, and a dict from each key to its node. The dict finds the node in O(1); because every node knows its neighbours both ways, unlinking it and putting it at the front are a few pointer changes, also O(1). Two empty sentinel nodes, head and tail, sit at the ends so the list is never empty and no special cases are needed.

What it costs, by counting. Each get or put does one dict lookup and at most about six pointer changes, whatever the size: O(1) time per call, so 1,000,000 requests take about 1,000,000 × 7 steps. Memory is O(capacity): one node and one dict entry per item.

class Node:
    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.nodes = {}                          # key -> its node in the list
        self.head, self.tail = Node(), Node()    # sentinels: head.next is the newest, tail.prev the oldest
        self.head.next, self.tail.prev = self.tail, self.head

    def _unlink(self, node):
        node.prev.next, node.next.prev = node.next, node.prev

    def _push_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        if key not in self.nodes:
            return -1
        node = self.nodes[key]
        self._unlink(node)                       # used just now: move it to the front
        self._push_front(node)
        return node.value

    def put(self, key, value):
        if key in self.nodes:
            self._unlink(self.nodes[key])
        node = Node(key, value)
        self.nodes[key] = node
        self._push_front(node)
        if len(self.nodes) > self.capacity:      # one too many: drop the oldest
            oldest = self.tail.prev
            self._unlink(oldest)
            del self.nodes[oldest.key]

cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
print(cache.get(1))
cache.put(3, 30)
print(cache.get(2), cache.get(3), cache.get(1))

Python's shortcut. collections.OrderedDict keeps keys in the order they were added and can move one to the end (move_to_end) or remove the first (popitem(last=False)) in O(1). Inside, it is the same dict plus linked list, so an LRU cache takes a few lines with it.

Mistakes and edge cases.

  • forgetting to move on get: reading a key is a use; if it doesn't move, the cache throws out a key you just used
  • evicting before inserting: when put updates a key that is already there, nothing should be thrown out
  • evicting from the wrong end: the oldest is at the back (tail.prev), not the front
  • forgetting the dict: unlinking the node but leaving its key in the dict makes get find a dead node
  • capacity 1: every new key throws out the one before it

Quiz

  1. What does this print?

    class Node:
        def __init__(self, key=None, value=None):
            self.key, self.value = key, value
            self.prev = self.next = None
    
    
    class LRUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.nodes = {}                          # key -> its node in the list
            self.head, self.tail = Node(), Node()    # sentinels: head.next is the newest, tail.prev the oldest
            self.head.next, self.tail.prev = self.tail, self.head
    
        def _unlink(self, node):
            node.prev.next, node.next.prev = node.next, node.prev
    
        def _push_front(self, node):
            node.prev, node.next = self.head, self.head.next
            self.head.next.prev = node
            self.head.next = node
    
        def get(self, key):
            if key not in self.nodes:
                return -1
            node = self.nodes[key]
            self._unlink(node)                       # used just now: move it to the front
            self._push_front(node)
            return node.value
    
        def put(self, key, value):
            if key in self.nodes:
                self._unlink(self.nodes[key])
            node = Node(key, value)
            self.nodes[key] = node
            self._push_front(node)
            if len(self.nodes) > self.capacity:      # one too many: drop the oldest
                oldest = self.tail.prev
                self._unlink(oldest)
                del self.nodes[oldest.key]
    
    c = LRUCache(2)
    c.put(1, 1)
    c.put(2, 2)
    c.get(1)
    c.put(3, 3)
    print(c.get(1), c.get(2), c.get(3))
  2. Why does an LRU cache need both a dict and a linked list?

    • The dict finds a key in O(1); the list keeps the use order and moves a node in O(1)
    • The list stores the values and the dict stores nothing
    • Python needs two structures for any class
  3. What is the time of one get or put in this design?

    • O(1)
    • O(log n)
    • O(n)
  4. A full cache gets put(k, v) for a key k that is already in it. What is thrown out?

    • Nothing: k's value changes and k moves to the front
    • The oldest key
    • k itself
  5. This cache throws out the key that was used most recently. Which line is wrong?

    def put(self, key, value):
        if key in self.items:
            self.items.move_to_end(key)
        self.items[key] = value
        if len(self.items) > self.capacity:
            self.items.popitem(last=True)

Coding tasks

  1. Write a class LRUCache(capacity) with get(key), which returns the key's value (or -1 if it is missing) and counts as a use, and put(key, value), which stores the value, counts as a use, and throws out the least recently used key when there are more than capacity keys. Both must take O(1) time. Each test makes a new cache, runs a list of calls on it and shows what each call returns (put returns None).

  2. Write a class EvictCounter(capacity): an LRU cache with get(key) and put(key, value) exactly as in the first task, plus an attribute evicted that counts how many keys have been thrown out so far. Use collections.OrderedDict. Each test runs a list of calls and then reads evicted.