LRU Cache

Build a fixed-size cache that drops the key unused for the longest time, with get and put in constant time.

A cache is a small, fast store that keeps some key-value pairs at hand, so they do not have to be fetched again. Design a cache that holds at most capacity pairs, with two methods. get(key) returns the value stored for key, or -1 if the key is not in the cache. put(key, value) stores the value, replacing any old value for that key.

A key counts as used each time get or put is called with it. When put adds a new key to a full cache, it first removes the key that was used least recently. Such a cache is called a least recently used (LRU) cache. Both methods must run in O(1) time on average.

Example 1
Input: capacity 2; put(1, 1), put(2, 2), get(1), put(3, 3), get(2), put(4, 4), get(1), get(3), get(4)
Output: get(1) = 1, get(2) = -1, get(1) = -1, get(3) = 3, get(4) = 4
Explanation: put(3, 3) removes key 2, because key 1 was just used; put(4, 4) removes key 1.
Solution

The Idea

You have probably seen a "Recent files" list in an editor. The file you just opened goes to the top, and when the list is full, the file at the bottom, the one you have not touched for the longest time, drops off. An LRU cache works the same way, with keys instead of files.

Follow Example 1, where the cache has room for two keys. put(1, 1) and put(2, 2) fill it. get(1) returns 1 and makes key 1 the most recently used, so key 2 is now the one used longest ago. When put(3, 3) arrives, the cache is full, so key 2 is removed, and get(2) returns -1. Next, put(4, 4) removes key 1, which by then is the key untouched the longest, so the second get(1) returns -1 too.

So on every call the cache must answer two questions quickly: where is the value for this key, and which key was used longest ago? A HashMap, Java's table that finds a value by its key, answers the first in one step. The second needs the keys kept in order of use, with a quick way to move any key to the front.

Think of the keys as a chain, most recently used at the front and least recently used at the back. If each link knows its neighbours on both sides, a key can be taken out of the middle by joining its two neighbours, and put back at the front. A chain like this is called a doubly linked list. Each element, a node, holds a pointer next to the node after it and a pointer prev to the node before it. Look at the picture below.

A doubly linked list between head and tail, most recently used first. After get(1) the order is key 1, key 2, so key 2 is least recently used. put(3, 3) on the full cache evicts key 2 from the tail end and adds key 3 at the front: key 3, key 1.

The row labelled "after get(1)" shows the chain once key 1 has just been used: head, key 1, key 2, tail. head and tail are two extra nodes that only mark the ends. Key 2 sits next to tail, so it is the least recently used, the next key to go. In the row labelled "after put(3, 3)", key 2 has been evicted, meaning removed, from that end, and key 3 went in at the front, right after head.

So the map finds a key's node in one step, and the list keeps the order of use. Moving a node to the front, or dropping the node next to tail, changes only a few pointers, however many keys the cache holds.

Solution Approach

Turning that idea into code means first seeing why a plain list of keys is too slow, then settling four things: what the map stores, how a node moves to the front, how the ends of the list are handled, and how eviction removes a key. A shorter version built on a Java class comes last, as an option.

A plain list of keys

Why not keep the keys in an ArrayList, in order of use? Finding a key in it means scanning the list, and moving the key to the front shifts the keys before it along by one. With n keys cached, a single call can take n steps, while both methods must take O(1).

What the map stores

What should the map point at? Not the value, but the key's node in the list. Then get finds the node in one step, reads the value from it, and already holds the node it has to move. The node carries the value, so no second map is needed.

Moving a node to the front

How does a node move in a fixed number of steps? First take it out: point the next of the node before it at the node after it, and the prev of the node after it back at the node before it. Then insert it right after head with four pointer changes. Both get and a put on a key already in the cache do this, because both count as a use.

Taking a node out needs the node before it, and prev gives it directly. A singly linked list, with only next pointers, would have to walk from the start to find that node.

Sentinel nodes at both ends

What about the first and last nodes, or an empty list? The first node would have no node before it and the last none after it, so every pointer change would need a check for null. The extra nodes head and tail remove those checks. They are created once, never removed and never hold a real key, so every real node always has a neighbour on both sides. Placeholder nodes like these are called sentinel nodes.

Evicting the least recently used key

When put meets a full cache, which node goes? The one just before tail, which is tail.prev. It must leave the list and the map, but the map is looked up by key, and the list only gives a node. That is why each node stores its key as well as its value: the key in the node tells the map which entry to remove.

Optional: a shorter version with LinkedHashMap

Is there something ready-made? Java's LinkedHashMap is a hash map that also threads its entries on a doubly linked list. Created with new LinkedHashMap<>(16, 0.75f, true), it orders the entries by access, least recently used first. After each put it calls its method removeEldestEntry, and a subclass that overrides it to return size() > capacity becomes an LRU cache in a few lines. Writing the list by hand, as the Java solution does, shows the same mechanism in the open.

Java Solution

The class has these parts, one for each piece of the approach:

  • Node: one cached pair, with its key, value and the prev and next pointers.
  • map: from key to node. get and put find nodes through it.
  • head and tail: the sentinel nodes. The node after head is the most recently used, the node before tail the least.
  • get: returns -1 for a key not in map; otherwise moves the key's node to the front and returns its value.
  • put: for a key already cached, updates the value and moves the node to the front. For a new key in a full cache, it first takes tail.prev out of the list and its key out of map. Then it adds the new node to map and at the front.
  • unlink, addFront and moveToFront: the pointer changes. moveToFront is unlink followed by addFront.
  • order: lists the keys from head to tail, only so that main can print the order of use.

The main method runs Example 1 and prints the order after each call that changes it, then updates a key in a full cache, and last tries a cache with room for one key.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LRUCache {

    private static class Node {
        int key;
        int value;
        Node prev;
        Node next;

        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private final int capacity;
    private final Map<Integer, Node> map = new HashMap<>();
    private final Node head = new Node(0, 0); // sentinel on the most recent side
    private final Node tail = new Node(0, 0); // sentinel on the least recent side

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        Node node = map.get(key);
        if (node == null) {
            return -1;
        }
        moveToFront(node);                 // used just now
        return node.value;
    }

    public void put(int key, int value) {
        Node node = map.get(key);
        if (node != null) {                // key already cached: update it
            node.value = value;
            moveToFront(node);
            return;
        }
        if (map.size() == capacity) {      // full: evict the least recently used
            Node lru = tail.prev;
            unlink(lru);
            map.remove(lru.key);
        }
        node = new Node(key, value);
        map.put(key, node);
        addFront(node);
    }

    private void moveToFront(Node node) {
        unlink(node);
        addFront(node);
    }

    private void unlink(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void addFront(Node node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }

    // keys from most to least recently used, for printing
    List<Integer> order() {
        List<Integer> keys = new ArrayList<>();
        for (Node n = head.next; n != tail; n = n.next) {
            keys.add(n.key);
        }
        return keys;
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        cache.put(1, 1);
        cache.put(2, 2);
        System.out.println("get(1) = " + cache.get(1) + ", order " + cache.order());
        cache.put(3, 3);
        System.out.println("put(3, 3): order " + cache.order());
        System.out.println("get(2) = " + cache.get(2));
        cache.put(4, 4);
        System.out.println("put(4, 4): order " + cache.order());
        System.out.println("get(1) = " + cache.get(1) + ", get(3) = " + cache.get(3)
                + ", get(4) = " + cache.get(4) + ", order " + cache.order());

        LRUCache updated = new LRUCache(2);       // an update counts as a use
        updated.put(1, 1);
        updated.put(2, 2);
        updated.put(1, 10);
        updated.put(3, 3);
        System.out.println("update: get(1) = " + updated.get(1) + ", get(2) = "
                + updated.get(2) + ", order " + updated.order());

        LRUCache one = new LRUCache(1);           // capacity 1
        one.put(1, 1);
        one.put(2, 2);
        System.out.println("capacity 1: get(1) = " + one.get(1) + ", get(2) = " + one.get(2));
    }
}

Running it prints:

Output
get(1) = 1, order [1, 2]
put(3, 3): order [3, 1]
get(2) = -1
put(4, 4): order [4, 3]
get(1) = -1, get(3) = 3, get(4) = 4, order [4, 3]
update: get(1) = 10, get(2) = -1, order [1, 3]
capacity 1: get(1) = -1, get(2) = 2

The first line, get(1) = 1, order [1, 2], is the top row of the picture. The second line, after put(3, 3), reads order [3, 1], the bottom row of the picture. Key 2 has gone, so get(2) on the next line returns -1. Next, put(4, 4) evicts key 1 and leaves [4, 3]. The fifth line gives the last three answers of Example 1: -1, 3 and 4.

Look at the line starting with update:. The cache held keys 1 and 2 when put(1, 10) changed key 1's value and moved its node to the front. So put(3, 3) evicted key 2, and get(1) returned 10. With the moveToFront call left out of that update, key 1 stays at the back. That version, run on the same calls, evicts key 1 instead and prints update: get(1) = -1, get(2) = 2, order [2, 3].

The last line comes from the cache with room for one key: put(2, 2) evicts key 1 straight away, so get(1) returns -1 and get(2) returns 2.

Complexity

Each call does one map lookup and a fixed number of pointer changes, however many keys are cached.

  • Time: O(1) on average for both get and put. A HashMap lookup takes constant time on average, and moving, adding or evicting a node changes a few pointers without walking the list. Only the printing helper order walks it.
  • Space: O(capacity). The map and the list hold one entry and one node per cached key, never more than capacity of each, plus the two sentinel nodes.

Evicting by how often a key is used, not how recently, is LFU Cache.