iq.lab
Python starts when a code cell comes near or you run one
07 Linked lists

Lesson 3 of 3

Designing an LRU cache

A cache with a size limit has to choose what to forget. An LRU cache forgets the key used longest ago, and a dict plus a doubly linked list makes every get and put O(1) on average.

About 1 hour 15 minutes, with the problem worked in it
By the end you can
  • Say which key an LRU cache evicts, and trace a sequence of calls by hand

  • Explain why keeping the order of use in a Python list costs O(capacity) per call

  • Unlink a node from a doubly linked list and append it before a tail sentinel in O(1)

  • Build an LRUCache class whose get and put both run in O(1) time

  • Name OrderedDict as the shortcut and answer the capacity, TTL and LFU follow-ups

A pipeline step enriches every event with the customer's record, which it fetches from a slow service. The same customers come up again and again, so you keep the records you fetched in memory and reuse them. Memory is limited, though: say you can hold 1,000 records. When customer 1,001 shows up, one record has to go. Which one?

A store like this is a cache: a small, fast store that keeps copies of things that are slow to fetch. When it is full, a good bet is to drop the record you have not needed for the longest time. That rule is called least recently used (LRU), and a cache that follows it is an LRU cache.

Building one is a classic interview question. You do not write one function; you design a class (as in module 5's min stack): a constructor, LRUCache(capacity), that makes an empty cache, and two methods (functions that belong to the class), get and put. Each call must take O(1) time on average: a number of steps that does not grow as the cache fills. Candidates keep reporting this design-as-coding family from recent rounds: caches like this one, a hit counter, an in-memory key-value store. We build it in three moves: the rule with a plain Python list, a structure that removes the list's slow step, and the class that joins them.

The rule: forget the least recently used key

What exactly counts as a use, and which key leaves? Three terms first.

  • Capacity is the most keys the cache may hold.
  • A use of a key is a get that finds it, or a put that stores it, whether the key is new or only gets a new value. A get for a missing key is not a use: there is nothing to use.
  • Eviction removes a key to make room. It happens only when a put brings a new key and the cache is already at capacity.

Picture the keys standing in a line, ordered by last use: the least recently used key at the front, the most recent at the back. Every use sends its key to the back. A new key joins at the back. Eviction removes the key at the front.

The plain way to keep that line is a Python list. The trace below uses three names: capacity, values (a dict from key to value) and order (the list of keys, front first). Two functions, get and put, share them. It runs the start of the first example from this lesson's problem: capacity 2, then put(4, 40), put(7, 70), get(4), put(9, 90) and get(7). Before you step through, predict: get(4) runs before put(9, 90), so which key does put(9, 90) evict?

Step throughThe list version on the first example
Step 1 of 36
Line 1 is about to run.
capacity = 2
values = {}
order = []
def get(key):
if key not in values:
return -1
order.remove(key)
order.append(key)
return values[key]
def put(key, value):
if key in values:
order.remove(key)
elif len(values) == capacity:
oldest = order.pop(0)
del values[oldest]
values[key] = value
order.append(key)
put(4, 40)
put(7, 70)
print(get(4))
put(9, 90)
print(get(7))
Names
no names yet
Output
(nothing printed yet)

So put(9, 90) evicted 7, not 4. What counts is the last use, not when a key was first stored: 4 arrived first, but get(4) sent it to the back. Try a longer sequence by hand, with an update in it.

On paperWhich key leaves?

On paper, run these calls on an LRU cache with capacity 3. After every call, write the order of use, least recently used first.

put(1, 10), put(2, 20), put(3, 30), get(1), put(2, 25), put(4, 40)

Which key does the last call evict?

Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

evicted key

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Where the list version is slow

The list version gives the right answers. Is it fast enough? Look at what each call does.

values is a dict, so key in values, values[key], values[key] = value and del values[oldest] take one step on average (module 3). order.append(key) is one step too. The two other list calls hide a walk. order.remove(key) scans from the front until it finds the key, then shifts every key after it one slot left to close the gap. The scan and the shift together touch every key in order, wherever the key sits. order.pop(0) removes the front item and shifts every other item one slot left. The cache holds up to capacity keys, so one call costs O(capacity). The problem's speed test fills the cache with 45,000 keys, and there a single get takes about 45,000 steps.

The promise is right; the notebook is slow. We want a line of keys with three moves that each take one step: find a key's place in the line, take it out from wherever it is, and add a key at the back. A dict already finds things in one step. The missing piece is a line you can cut a key out of without shifting the rest.

Quick checkThe hidden walk

The list version holds 1,000 keys. Which line of its get can take about 1,000 steps?

def get(key):
    if key not in values:
        return -1
    order.remove(key)
    order.append(key)
    return values[key]

Choose one answer, then check.

Moving a node in one step

Which structure lets you cut an item out of the middle without shifting the rest? A linked list. Each item lives in its own node, and the nodes point at each other, so taking one out means changing a few pointers. Nothing shifts.

In the first lesson of this module, a node had two fields: val, its value, and next, the node after it. To take a node out, the node before it must point past it. With next alone, finding the node before means walking from the front, so a cache full of keys would pay O(capacity) again. A doubly linked list gives every node a second pointer, prev, to the node before it. Holding a node, you reach both of its neighbors in one step. Our nodes also store their key, for a reason the next section shows: Node(key, val) has the fields key, val, prev and next.

The cache needs only two moves:

  • Unlink a node: point its two neighbors at each other. That is two pointer changes, node.prev.next = node.next and node.next.prev = node.prev.
  • Append a node at the newest end: put it after the newest node. That is four pointer changes: the node's own prev and next, and one pointer on each of its new neighbors.

The ends are the trouble. In a plain doubly linked list, the first node has no node before it, so its prev is None, and None.next raises an AttributeError. Checking for None at each end, in every method, makes long code with many chances for a bug. The fix is two sentinels. A sentinel is a spare node that holds no real key and never leaves the list: the dummy head from the first lesson of this module, kept for good, and here there is one at each end. head sits before the oldest node and tail after the newest. (In the first lesson, tail named the last real node of a list being built. Here tail is the spare node after the newest real one.) With sentinels, every real node has a node on both sides, never None, even when it is the only real node, so unlink and append never check for None.

The trace below builds a list by hand: head, nodes for keys 1, 2 and 3 (values 10, 20 and 30), then tail. Then key 2 is used, so its node moves to the newest end. Under "Linked nodes" the drawing follows the next arrows and labels each node with its val, so the sentinels show as 0. It opens at step 38 with the list built; press First if you want to watch it being built. Before you step through, guess: when unlink(two) runs, whose fields change? Node 20's own, its two neighbors', or all three?

Step throughMoving a node to the newest end
Step 38 of 49
Line 25 is about to run.
Key 2 is used now, so its node moves to the newest end.
  • tail.prev: None → Node(30)
  • three.next: None → Node(0)
class Node:
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = None
self.next = None
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def append(node):
last = tail.prev
last.next = node
node.prev = last
node.next = tail
tail.prev = node
head, tail = Node(), Node()
one, two, three = Node(1, 10), Node(2, 20), Node(3, 30)
head.next, one.prev = one, head
one.next, two.prev = two, one
two.next, three.prev = three, two
three.next, tail.prev = tail, three
unlink(two)
append(two)
Names
Nodeclass Node
unlinkfunction unlink
appendfunction append
head→ Node(0)
tail→ Node(0)
one→ Node(10)
two→ Node(20)
three→ Node(30)
Linked nodes
head0one10two20three30tail0None
Output
(nothing printed yet)

So the answer to the guess: unlinking changes the neighbors, not the node. Node 20 kept its old prev and next until append overwrote them, and that does no harm: once both neighbors skip it, a walk from head never reaches it.

Work it outCount the pointer changes

In the trace above, moving node 20 to the newest end ran unlink(two) and then append(two). Count the lines that assigned to a prev or next field (lines such as last.next = node). How many ran in total?

field assignments

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Recap. A doubly linked list with sentinels moves any node you hold in six pointer changes, whatever its length. What it cannot do is find a node by key. That is the dict's job, and the next section joins the two. First, write the two moves yourself, in a mirror image.

Code itThe mirror image

Some people keep the order the other way round: newest right after head, oldest right before tail. Write that version's two moves in Recency. push_front(node) puts a node right after head. pop_back() unlinks the oldest node and returns its key, or returns None when there are no real nodes. unlink and keys are written for you. Then press Watch it run.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

The cache: a dict of nodes plus the list

How do the dict and the list fit together? The dict maps each key to its node, so finding a key's place in the line takes one step. The list keeps the nodes in order of use, so moving a key to the back, or evicting from the front, takes a few pointer changes. Together they make every call O(1).

Each node stores its key, and eviction is why. When the cache is full, the list says which node to evict: head.next. Its dict entry has to go too, and deleting that entry needs the key. The node carries it.

In the interview this is a class. A reminder from the prefix sums lesson: a class bundles a notebook with the methods that use it. __init__ runs once when the object is made, every method receives the object as self, and names stored on it, such as self.nodes, survive from one call to the next. The two moves become helper methods, _unlink and _append; a leading underscore marks a method meant only for the class's own use. Then the public methods are short:

  1. get(key): look up the node. If there is none, return -1. Otherwise unlink it, append it (it is now the most recent) and return its val.
  2. put(key, value) for a key already present: change its val, unlink it, append it. Nothing is evicted, since the number of keys stays the same.
  3. put(key, value) for a new key: if the cache is full, unlink head.next and delete its key from the dict. Then make a node, store it in the dict and append it.

put asks "is the key already here?" before "is the cache full?" Asked the other way round, an update in a full cache would evict a key for nothing.

The trace runs the same first example on the class. Inside the cache's methods, self is the same object as cache, so the trace hides self; cache in the Names box shows the nodes dict. The line head, tail = cache.head, cache.tail only gives the sentinels tags in the drawing. The trace opens at step 33, with the cache built and empty. Before you step through, predict: when put(9, 90) needs room, which node does it unlink, and how does it find that node without a search?

Step throughThe LRU cache on the first example
Step 33 of 116
Line 37 is about to run inside put.
  • called put(key=4, value=40)
class Node:
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.nodes = {}
self.head = Node()
self.tail = Node()
self.head.next = self.tail
self.tail.prev = self.head
def _unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _append(self, node):
last = self.tail.prev
last.next = node
node.prev = last
node.next = self.tail
self.tail.prev = node
def get(self, key):
node = self.nodes.get(key)
if node is None:
return -1
self._unlink(node)
self._append(node)
return node.val
def put(self, key, value):
node = self.nodes.get(key)
if node is not None:
node.val = value
self._unlink(node)
self._append(node)
return
if len(self.nodes) == self.capacity:
oldest = self.head.next
self._unlink(oldest)
del self.nodes[oldest.key]
node = Node(key, value)
self.nodes[key] = node
self._append(node)
cache = LRUCache(2)
head, tail = cache.head, cache.tail
cache.put(4, 40)
cache.put(7, 70)
print(cache.get(4))
cache.put(9, 90)
print(cache.get(7))
Names
cacheLRUCachecapacity=2nodes={}head=Node(0)tail=Node(0)
Nodeclass Node
LRUCacheclass LRUCache
head→ Node(0)
tail→ Node(0)
put( )
key4
value40
Linked nodes
head0tail0None
Output
(nothing printed yet)

Some steps in the middle look tangled, and that is expected. A moving node still points at its old neighbors for a few steps, as in the last trace. The evicted node 70 keeps a row of its own until put returns, because oldest still names it; then no name reaches it, and it leaves the drawing.

Why it is correct. Every use ends with _append, so the key used last always sits right before tail, and no other key changes its place. So the list stays ordered by last use, and head.next is always the least recently used key when an eviction needs it. The dict and the list change together in every method, so they always hold the same keys. It is the list version's promise, kept by a faster notebook.

Put get together first.

Put in orderPut get together

Put the lines of get in order. It returns the value stored for key and makes key the most recently used, or returns -1 when key is missing. Indentation is part of each line. Two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • if node is None:
    • node = self.nodes.get(key)
    • self._unlink(node)
    • return -1
    • def get(self, key):
    • self._append(node)
    • return node
    • return node.val
    • node = self.nodes[key]

    The order of the two checks in put is the classic slip. See what it breaks.

    Quick checkFull first, or here first?

    This put checks whether the cache is full before it checks whether the key is already there:

    def put(self, key, value):
        if len(self.nodes) == self.capacity:
            oldest = self.head.next
            self._unlink(oldest)
            del self.nodes[oldest.key]
        node = self.nodes.get(key)
        if node is not None:
            node.val = value
            self._unlink(node)
            self._append(node)
            return
        node = Node(key, value)
        self.nodes[key] = node
        self._append(node)

    The cache has capacity 2, and get is the correct one from the lesson. The calls are put(1, 1), put(2, 2), put(2, 22), then get(1). What happens?

    Choose one answer, then check.

    Now write the whole class yourself, from a blank editor if you can. The hints climb from a nudge to the full plan. One naming difference: the problem's solution calls the node field value; this lesson used val, the name ListNode uses. Either works.

    mediumDesign as codingLinked listsHash maps and sets target 25 min

    LRU cache

    Build a class LRUCache that stores up to capacity key-value pairs and, when it runs out of room, forgets the least recently used key: the key whose last use is furthest in the past. A key is used each time a get finds it or a put stores it.

    • LRUCache(capacity) makes an empty cache.
    • get(key) returns the value stored for key, or -1 if the key is not in the cache. A get that finds the key counts as a use.
    • put(key, value) stores value under key, replacing the old value if the key is already there. It counts as a use. If the key is new and the cache already holds capacity keys, first remove the least recently used key.

    Both methods must take O(1) time on average, however many keys the cache holds.

    Example 1
    InputLRUCache(2), put(4, 40), put(7, 70), get(4), put(9, 90), get(7), get(9)Outputget(4) returns 40, get(7) returns -1, get(9) returns 90

    get(4) made key 4 the most recent, so put(9, 90) removed key 7, the least recently used.

    Example 2
    InputLRUCache(2), put(1, 10), put(2, 20), put(1, 15), put(3, 30), get(1), get(2)Outputget(1) returns 15, get(2) returns -1

    Updating key 1 counts as a use, so key 2 is the one removed.

    Constraints
    • 1 ≤ capacity ≤ 105

    • Keys and values are integers, and values are never negative, so -1 always means "missing".

    • Up to 2 × 105 calls in total.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Beyond the two examples, the tests check the edge cases: a missing key, a stored value of 0 (test node is None; a test such as if not value: treats 0 as missing, because if counts 0 as false), capacity 1, an update in a full cache, an evicted key that comes back, and the order of evictions. The last test makes about 92,000 calls on a cache of 45,000 keys within 1 second. That is where the list version runs out of time: each of its reads costs about 45,000 steps.

    After it works: the shortcut and the follow-ups

    What should you have ready once the class works? The shortcut Python already offers, and answers to the follow-ups. First the shortcut. collections.OrderedDict is a dict that remembers the order of its keys and can reorder them in one step. move_to_end(key) sends a key to the back, and popitem(last=False) removes and returns the front pair. Inside, it is a hash table plus a doubly linked list, the design you built above. (A plain dict also keeps its keys in the order they were added, but it has no move_to_end.) With it, the whole cache is a few lines:

    from collections import OrderedDict
    
    class LRUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.data = OrderedDict()  # least recently used first
    
        def get(self, key):
            if key not in self.data:
                return -1
            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)
            self.data[key] = value
            if len(self.data) > self.capacity:
                self.data.popitem(last=False)

    Name it in the interview, and say what each call costs: move_to_end and popitem change a few links, so every get and put is still O(1) on average. The linked list is the heart of this question, so the interviewer may ask you to build it by hand. Say you would, and do it if asked: that is the class you wrote above.

    One detail decides whether the shortcut is right: what does assigning to a key that is already in an OrderedDict do to its place? Predict it.

    PredictOrderedDict moves

    Type exactly what this prints. list(recent) lists the keys in their current order, front first.

    from collections import OrderedDict
    
    recent = OrderedDict()
    recent[4] = 40
    recent[7] = 70
    recent[9] = 90
    recent.move_to_end(4)
    print(list(recent))
    print(recent.popitem(last=False))
    recent[9] = 95
    print(list(recent))
    

    That is why the shortcut's put calls move_to_end for a key that is already there: assigning to a key that is already in an OrderedDict leaves the key in its old place. Without move_to_end, an update would not count as a use.

    Expect follow-ups. For this design, three natural ones are:

    • The capacity changes. Add resize(new_capacity): store the new capacity, then evict from head.next until the cache fits. Each eviction is O(1), so a resize costs one step per key removed.
    • Keys expire after a fixed time (a TTL, time to live). Store an expiry time in each node when it is written. In get, an expired node is unlinked, deleted from the dict and reported as missing. Every call stays O(1). The catch to mention: an expired key that nobody reads still takes room until eviction reaches it.
    • Evict the least frequently used key instead (LFU). Keep a use count per key, one doubly linked list per count in order of use, and the smallest count present. A use moves a key from list c to the back of list c + 1; if list c empties and c was the smallest, the smallest becomes c + 1. A new key joins list 1, and 1 becomes the smallest. Eviction takes the front of the smallest count's list. Every call is still O(1); this is LeetCode 460.

    Last, say the design out loud, the way you would before typing.

    Say itSay the design

    Explain your LRU cache to an interviewer before you type. Cover the notebook, the promise, what each call costs and why, and what you would say about OrderedDict. Use a few plain sentences.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint