LRU Cache
The problem
Section titled “The problem”Build a cache with a fixed capacity. get(key) returns the value or -1 if absent.
put(key, value) inserts or updates. When a put pushes the size past capacity, evict
the least recently used key. Both get and put count as a “use”. Both must run in
O(1) average time.
capacity 2: put(1,1) put(2,2) get(1)->1 put(3,3) (evicts 2) get(2)->-1Key insight
Section titled “Key insight”Two needs pull in opposite directions. You need to find a key in O(1), which is a hash map. You also need to know the usage order and move any entry to “most recent” in O(1), which a map can’t do. A doubly linked list can: if you hold a node, you can unlink it and reinsert it at the front without searching.
So combine them. The list is ordered from most to least recent. The map goes from key to
list node. get looks up the node, moves it to the front and returns its value. put
puts a new node at the front, and if the size is over capacity, drops the node just before
the tail. Two sentinel nodes (fake head and tail) mean you never check for null
neighbors. Each node also stores its key, so eviction can delete the map entry.
In an interview, OrderedDict (Python) or LinkedHashMap (Java) does all this in a few
lines. Mention it, but expect to be asked to build it by hand.
Show solutionHide solution
class Node: def __init__(self, key=0, val=0): self.key, self.val = key, val self.prev = self.next = None
class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.nodes = {} # key -> node, for O(1) lookup self.head, self.tail = Node(), Node() # sentinels: head.next is the most recent self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node: Node) -> None: node.prev.next, node.next.prev = node.next, node.prev
def _push_front(self, node: Node) -> None: node.prev, node.next = self.head, self.head.next self.head.next.prev = node self.head.next = node
def get(self, key: int) -> int: if key not in self.nodes: return -1 node = self.nodes[key] self._unlink(node) self._push_front(node) # now the most recently used return node.val
def put(self, key: int, value: int) -> None: if key in self.nodes: self._unlink(self.nodes[key]) node = self.nodes[key] = Node(key, value) self._push_front(node) if len(self.nodes) > self.capacity: lru = self.tail.prev # least recently used sits before the tail sentinel self._unlink(lru) del self.nodes[lru.key]class Node { key: number; val: number; prev: Node | null = null; next: Node | null = null; constructor(key = 0, val = 0) { this.key = key; this.val = val; }}
export class LRUCache { private capacity: number; private nodes = new Map<number, Node>(); // key -> node, for O(1) lookup private head = new Node(); // sentinels: head.next is the most recent private tail = new Node();
constructor(capacity: number) { this.capacity = capacity; this.head.next = this.tail; this.tail.prev = this.head; }
private unlink(node: Node): void { node.prev!.next = node.next; node.next!.prev = node.prev; }
private pushFront(node: Node): void { node.prev = this.head; node.next = this.head.next; this.head.next!.prev = node; this.head.next = node; }
get(key: number): number { const node = this.nodes.get(key); if (!node) return -1; this.unlink(node); this.pushFront(node); // now the most recently used return node.val; }
put(key: number, value: number): void { const old = this.nodes.get(key); if (old) this.unlink(old); const node = new Node(key, value); this.nodes.set(key, node); this.pushFront(node); if (this.nodes.size > this.capacity) { const lru = this.tail.prev!; // least recently used sits before the tail sentinel this.unlink(lru); this.nodes.delete(lru.key); } }}import java.util.HashMap;import java.util.Map;
class LRUCache { private static class Node { int key, val; Node prev, next;
Node(int key, int val) { this.key = key; this.val = val; } }
private final int capacity; private final Map<Integer, Node> nodes = new HashMap<>(); // key -> node, for O(1) lookup private final Node head = new Node(0, 0), tail = new Node(0, 0); // sentinels: head.next is the most recent
public LRUCache(int capacity) { this.capacity = capacity; head.next = tail; tail.prev = head; }
private void unlink(Node node) { node.prev.next = node.next; node.next.prev = node.prev; }
private void pushFront(Node node) { node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; }
public int get(int key) { Node node = nodes.get(key); if (node == null) return -1; unlink(node); pushFront(node); // now the most recently used return node.val; }
public void put(int key, int value) { Node old = nodes.get(key); if (old != null) unlink(old); Node node = new Node(key, value); nodes.put(key, node); pushFront(node); if (nodes.size() > capacity) { Node lru = tail.prev; // least recently used sits before the tail sentinel unlink(lru); nodes.remove(lru.key); } }}Complexity
Section titled “Complexity”- Time: O(1) per operation — a hash lookup plus a constant number of pointer changes.
- Space: O(capacity) — at most
capacitynodes and map entries exist at once.
Watch out for
Section titled “Watch out for”- Updating an existing key must also refresh its recency. Here it unlinks the old node first, so the size doesn’t grow and nothing is wrongly evicted.
- Storing the key in each node. Without it you can’t remove the evicted node’s entry from the map.
- Pointer order when relinking. Set the new node’s
prevandnextbefore changing its neighbors’ pointers. Draw it out once. - A failed
getchanges nothing. Return-1without touching the list.
Variations
Section titled “Variations”LFU Cache (LeetCode 460)
Section titled “LFU Cache (LeetCode 460)”Evict the least frequently used key, breaking ties by least recent. The trick: keep a map from key to node and a map from frequency to a doubly linked list of keys with that frequency, plus the current minimum frequency. Each use moves a key up one list.
Design Linked List (LeetCode 707)
Section titled “Design Linked List (LeetCode 707)”Implement get, addAtHead, addAtTail, addAtIndex and deleteAtIndex. The trick:
the same sentinel nodes used here make every insert and delete branch-free.
Insert Delete GetRandom O(1) (LeetCode 380)
Section titled “Insert Delete GetRandom O(1) (LeetCode 380)”Support insert, remove and random pick in O(1). The trick: another map-plus-structure pairing: an array for random access and a map from value to array index. To remove, swap the element with the last one and pop.