AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

See it run

A map finds the node, a list remembers the order. Watch both change in every call.

Operations

Fill it, then evict

Four puts into a cache for three. The fourth one pays with the node at the back.

Step 1 of 7

Empty

clientcallercacheLruCachecapacity3nodesnoneorderRecencyListfrontnonebacknone

A map without keys, and a list with two sentinels and nothing between them.

Step 1: Empty

def put(self, key, value):    node = self._nodes.get(key)    if node is not None:        node.value = value        self._order.touch(node)        return None    evicted = None    if len(self._nodes) == self.capacity:        evicted = self._evict()    node = Node(key, value)    self._nodes[key] = node    self._order.push_front(node)    return evicted
Cost
O(1)
Guarantee
Never above 3
Array, 3 entries
3 looks
Array, 1,000,000
1,000,000 looks

Evict first, insert second: the limit is never broken, not even for a moment.

In the real world

The same lru cache doing real jobs. Pick one and step through it.

A report reads a million rows once. What is left of the hot entries?

Step 1 of 4

Warm

1234
plainABCD
splitA protectedB protectedC trialD trial

Both caches hold the hot keys A, B, C, D. The second one is split: two protected places, two on trial.

Step 1: Warm

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reading without moving

    critical

    The order becomes the order of writing. That is FIFO, and it throws out the most popular key.

    Wrong
    def get(self, key):    return self._nodes[key].value
    Right
    node = self._nodes.get(key)if node is None:    return defaultself._order.touch(node)return node.value
  • Evicting from one structure only

    critical

    The map grows for ever and leads to nodes that are in no list.

    Wrong
    self._order.unlink(node)
    Right
    self._order.unlink(node)del self._nodes[node.key]
  • Asking full before known

    critical

    An update of a full cache evicts an entry that was not in the way.

    Wrong
    if len(self._nodes) == self.capacity:    self._evict()node = self._nodes.get(key)
    Right
    node = self._nodes.get(key)if node is not None:    ...                      # update and returnif len(self._nodes) == self.capacity:    self._evict()
  • Two writes in the wrong order

    major

    After the first line head.next is the node itself. It now points at itself, and every walk hangs.

    Wrong
    self._head.next = nodeself._head.next.prev = node
    Right
    self._head.next.prev = nodeself._head.next = node
  • Upgrading a read lock

    critical

    In Java a thread that holds the read lock and asks for the write lock waits for itself, for ever.

    Wrong
    readLock.lock();...writeLock.lock();   // never returns
    Right
    lock.lock();        // one lock, get and put
  • Loading under the lock

    major

    One slow database call stops every hit of every other key.

    Wrong
    with self._lock:    value = self._load(key)
    Right
    # note the load under the lock, do it outside,# let the others wait for that one result

Interview tips

  • Open with

    • Map: find the node.
    • List: know the order.
    • Node: knows its key.
  • Draw

    • head, two nodes, tail.
    • The four writes.
    • The map pointing at nodes.
  • Prove it

    • Trace capacity 1.
    • Trace an update when full.
    • Map size = list length.
  • Never

    • A search in get.
    • A read lock around get.
    • A load under the lock.