AlgoViz

Design an LRU cache

medium 85 min

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

Watch lesson4:49

Verify

Trace it with real values

The point: do not say done. Put eight calls through a cache for three and write the order after each.

Eight calls

Capacity 3

CallBranchOrder, front firstMapAnswer
put(1, 100)new11nobody evicted
put(2, 200)new2 11 2nobody evicted
put(3, 300)new3 2 11 2 3nobody evicted
get(1)hit1 3 21 2 3100
put(4, 400)full, new4 1 31 3 4evicted (2, 200)
get(2)miss4 1 31 3 4nothing
put(3, 999)known3 4 11 3 4nobody evicted
put(5, 500)full, new5 3 43 4 5evicted (1, 100)
The fifth line is the test of get: without the touch in line four, key 1 would have gone.
Python
from collections import OrderedDictclass Model:    """The same rules with a dictionary that remembers its order. Last is most recent."""    def __init__(self, capacity):        self.capacity, self.data = capacity, OrderedDict()    def get(self, key):        if key not in self.data:            return None        self.data.move_to_end(key)        return self.data[key]    def put(self, key, value):        if key in self.data:            self.data.move_to_end(key)        elif len(self.data) == self.capacity:            self.data.popitem(last=False)        self.data[key] = valuem = Model(3)for step in ["put 1 100", "put 2 200", "put 3 300", "get 1", "put 4 400", "get 2", "put 3 999", "put 5 500"]:    name, key, *rest = step.split()    out = m.put(key, rest[0]) if name == "put" else m.get(key)    print(f"{step:10} order {list(reversed(m.data))} answer {out}")
The same eight calls on a short model. Run it and compare with your board.
Edit and run it in your browser

Small inputs that break large designs

InputMust happenWhat it finds
Capacity 1: put a, put b, get ab in, a out, a missLists that cannot have one node
Capacity 1: put a, put a againSame node, new valueFull asked before known
get on an empty cacheA missTouching nothing
get of the node that is first alreadyNo changeA node linked to itself
put of the key that is last, when fullMoved, nobody evictedEvicting the node you are updating
Capacity 0An error when createdEvicting a sentinel
remove, then put of another keyRoom was made, nobody evictedSizes that are counted by hand

Four sentences that are true after every call

  1. 1

    Same nodes

    Each map value is in the list, each node of the list is in the map under its own key.

  2. 2

    Within the limit

    The size is at most the capacity.

  3. 3

    Neighbours agree

    For each node, node.next.prev is the node, and so is node.prev.next.

  4. 4

    Front means last used

    The key of the last successful get or put is at the front.

The question to ask at each line of put

Between the last two lines of put the answer is yes for a moment. That is fine for one thread, and the reason why a lock must cover the whole method.