Design Data Structures · Pattern 2 of 10

Linked list designs: LRU cache and friends

A doubly linked list can move or remove any node in O(1) if you already hold it, and a hash map from key to node gives you that node. Together they make an LRU cache, and with buckets per count, LFU and All O'one.

3 variations · 5 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Evict the least recently (or least frequently) used item
  • Move an item to the front or back when it is touched
  • Insert or delete at the front, middle or back in O(1)
  • Get the max and min key by count, all in O(1)

The template

Linked Lists
class LRUCache {
    class Node { int key, val; Node prev, next; Node(int k, int v) { key = k; val = v; } }
    Map<Integer, Node> map = new HashMap<>();
    Node head = new Node(0, 0), tail = new Node(0, 0);   // sentinels: head.next is the newest
    int capacity;
    LRUCache(int capacity) { this.capacity = capacity; head.next = tail; tail.prev = head; }
    int get(int key) {
        Node n = map.get(key);
        if (n == null) return -1;
        unlink(n); addFront(n);                          // now the most recently used
        return n.val;
    }
    void put(int key, int value) {
        Node n = map.get(key);
        if (n != null) { n.val = value; unlink(n); addFront(n); return; }
        if (map.size() == capacity) {                    // evict before inserting
            Node lru = tail.prev;
            unlink(lru); map.remove(lru.key);
        }
        n = new Node(key, value);
        map.put(key, n); addFront(n);
    }
    void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
    void addFront(Node n) { n.prev = head; n.next = head.next; head.next.prev = n; head.next = n; }
}

The variations

  1. 1Build the list yourself

    Keep a dummy head (and tail) so there is always a node before the one you change. To reach index i, walk from whichever end is closer. Track the size so bad indexes are rejected in O(1).

  2. 2Two halves for the middle

    Split the items into a front half and a back half (two deques or lists) and rebalance after each change so the front is never bigger than the back by more than one. The middle is then always at the boundary.

  3. 3Hash map + doubly linked list

    The map finds the node, the list keeps the use order. On every use, unlink the node and put it at the front; evict from the back. LFU keeps one such list per frequency plus the current minimum frequency. All O'one keeps a list of count buckets, each holding its keys, so the first and last buckets give the min and max.

    Worked example LRU Cache Medium Read the solution

Mistakes to avoid

  • Forgetting to delete the evicted key from the map: the map grows and get returns a ghost.
  • Not moving the node on get, or on put of an existing key: both count as a use.
  • Skipping sentinel nodes: then every insert and remove needs special cases for the first and last node.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.