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 capacityget(key)keyput(key, value)
A key counts as used each time getputput
Example 1
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.
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)put(2, 2)get(1)put(3, 3)get(2)put(4, 4)get(1)
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
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 nextprev
The row labelled "after get(1)" shows the chain once key 1 has just been used: headtailheadtailtailhead
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
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
What the map stores
What should the map point at? Not the value, but the key's node in the list. Then get
Moving a node to the front
How does a node move in a fixed number of steps? First take it out: point the nextprevheadgetput
Taking a node out needs the node before it, and prevnext
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 nullheadtail
Evicting the least recently used key
When puttailtail.prev
Optional: a shorter version with LinkedHashMap
Is there something ready-made? Java's LinkedHashMapnew LinkedHashMap<>(16, 0.75f, true)putremoveEldestEntrysize() > capacity
Java Solution
The class has these parts, one for each piece of the approach:
: one cached pair, with itsNode ,key and thevalue andprev pointers.next : from key to node.map andget find nodes through it.put andhead : the sentinel nodes. The node aftertail is the most recently used, the node beforehead the least.tail : returns -1 for a key not inget ; otherwise moves the key's node to the front and returns its value.map : 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 takesput out of the list and its key out oftail.prev . Then it adds the new node tomap and at the front.map ,unlink andaddFront : the pointer changes.moveToFront ismoveToFront followed byunlink .addFront : lists the keys fromorder tohead , only so thattail can print the order of use.main
The main
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:
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]put(3, 3)order [3, 1]get(2)put(4, 4)[4, 3]
Look at the line starting with update:put(1, 10)put(3, 3)get(1)moveToFrontupdate: get(1) = -1, get(2) = 2, order [2, 3]
The last line comes from the cache with room for one key: put(2, 2)get(1)get(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
lookup takes constant time on average, and moving, adding or evicting a node changes a few pointers without walking the list. Only the printing helperHashMap walks it.order - Space: O(capacity). The map and the list hold one entry and one node per cached key, never more than
of each, plus the two sentinel nodes.capacity
Evicting by how often a key is used, not how recently, is