Design an LRU cache
28 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Design an LRU Cache is one of the most common software engineering interview questions. It pairs a HashMap with a Doubly Linked List so get and put run in O(1) time.
Why we pair a HashMap with a doubly linked list
An LRU (Least Recently Used) cache keeps a fixed number of items and, when full, evicts the item whose last get or put happened farthest in the past.
An LRU (Least Recently Used) cache holds at most capacity key-value pairs. Calling get(key) returns its value and marks it most recently used, or returns -1 if absent. Calling put(key, value) inserts or updates (key, value) and evicts the least recently used key when full.
Example 1 · Brute force: keep entries in a list and scan it on every call (O(n) per get and put)
import java.util.LinkedList;
public class SlowLruDemo { static class SlowLru { private final int capacity; private final LinkedList<int[]> entries = new LinkedList<>();
SlowLru(int capacity) { this.capacity = capacity; }
int get(int key) { for (int[] e : entries) { if (e[0] == key) { entries.remove(e); entries.addFirst(e); return e[1]; } } return -1; }
void put(int key, int value) { for (int[] e : entries) { if (e[0] == key) { entries.remove(e); break; } } entries.addFirst(new int[]{key, value}); if (entries.size() > capacity) entries.removeLast(); } }
public static void main(String[] args) { SlowLru cache = new SlowLru(2); cache.put(1, 10); cache.put(2, 20); System.out.println(cache.get(1)); cache.put(3, 30); System.out.println(cache.get(2)); System.out.println(cache.get(3)); }}10 -1 30
What this code does
- The front of the list is the most recently used entry and the back is the least recently used, so eviction is
removeLast(). - Finding a key means scanning the list, and
remove(e)scans again: everygetandputcosts O(n). - The
HashMapplus doubly linked list in the next example finds and moves an entry in O(1).
Example 2 · Optimal: HashMap plus sentinel doubly linked list (O(1) get and put)
import java.util.HashMap;import java.util.Map;
public class LRUCacheDemo { static class LRUCache { static class DNode { int key, val; DNode prev, next; DNode(int key, int val) { this.key = key; this.val = val; } }
private final int capacity; private final Map<Integer, DNode> map = new HashMap<>(); private final DNode head = new DNode(0, 0); private final DNode tail = new DNode(0, 0);
public LRUCache(int capacity) { this.capacity = capacity; head.next = tail; tail.prev = head; }
private void unlink(DNode node) { node.prev.next = node.next; node.next.prev = node.prev; }
private void addFirst(DNode node) { node.next = head.next; node.prev = head; head.next.prev = node; head.next = node; }
public int get(int key) { DNode node = map.get(key); if (node == null) return -1; unlink(node); addFirst(node); return node.val; }
public void put(int key, int value) { DNode node = map.get(key); if (node != null) { node.val = value; unlink(node); addFirst(node); return; } DNode fresh = new DNode(key, value); map.put(key, fresh); addFirst(fresh); if (map.size() > capacity) { DNode lru = tail.prev; unlink(lru); map.remove(lru.key); } } }
public static void main(String[] args) { LRUCache cache = new LRUCache(2); cache.put(1, 10); cache.put(2, 20); System.out.println("get(1): " + cache.get(1)); cache.put(3, 30); System.out.println("get(2): " + cache.get(2)); cache.put(4, 40); System.out.println("get(1): " + cache.get(1)); System.out.println("get(3): " + cache.get(3)); System.out.println("get(4): " + cache.get(4)); }}get(1): 10 get(2): -1 get(1): -1 get(3): 30 get(4): 40
What this code does
- Calling
cache.get(1)moves key1tohead.next, leaving key2as the LRU entry attail.prev. - When
cache.put(3, 30)exceeds capacity2,tail.prev(key2) is unlinked and removed frommapin O(1) time.
No single data structure gives O(1) for both operations. A HashMap gives O(1) lookup by key, but has no recency order. A Doubly Linked List moves any known DNode in O(1) time, but finding a key takes O(n) time. The solution is to store DNode references inside a HashMap<Integer, DNode>! Now map.get(key) finds DNode in O(1) time, and the doubly linked list moves it in O(1) time.
The pieces of the design:
HashMap<Integer, DNode>: mapskey -> DNodein O(1) time so we never scan the linked list.- Doubly Linked List (
head <-> ... <-> tail): orders MRU athead.nextdown to LRU attail.prev. - Why each
DNodestores bothkeyandval: When evictingDNode lru = tail.prev, we needlru.keyto callmap.remove(lru.key).
get and put in O(1)
Both operations are built from two helpers on the sentinel list from Lesson 7: unlink(node) detaches a node, and addFirst(node) inserts it right after head.
get(key): Look upDNode node = map.get(key). Ifnode == null, return-1; otherwise callunlink(node); addFirst(node);and returnnode.val.put(key, value)whenkeyexists: Look upDNode node = map.get(key), updatenode.val = value, and callunlink(node); addFirst(node);.put(key, value)whenkeyis new: CreateDNode node = new DNode(key, value), put(key, node)intomap, and calladdFirst(node). Ifmap.size() > capacity, evictDNode lru = tail.prevviaunlink(lru)andmap.remove(lru.key).
Example 3 · Tracing the MRU-to-LRU Chain After Every Operation
import java.util.HashMap;import java.util.Map;
public class LRUCacheTraceDemo { static class DNode { int key, val; DNode prev, next; DNode(int k, int v) { key = k; val = v; } }
static class TraceableLRU { final int cap; final Map<Integer, DNode> map = new HashMap<>(); final DNode head = new DNode(0, 0), tail = new DNode(0, 0); TraceableLRU(int cap) { this.cap = cap; head.next = tail; tail.prev = head; }
void unlink(DNode x) { x.prev.next = x.next; x.next.prev = x.prev; } void addFirst(DNode x) { x.next = head.next; x.prev = head; head.next.prev = x; head.next = x; }
void put(int k, int v) { if (map.containsKey(k)) { DNode x = map.get(k); x.val = v; unlink(x); addFirst(x); } else { DNode x = new DNode(k, v); map.put(k, x); addFirst(x); if (map.size() > cap) { DNode lru = tail.prev; unlink(lru); map.remove(lru.key); } } printState("put(" + k + "," + v + ")"); }
int get(int k) { DNode x = map.get(k); if (x != null) { unlink(x); addFirst(x); } printState("get(" + k + ")"); return x == null ? -1 : x.val; }
void printState(String op) { StringBuilder sb = new StringBuilder(String.format("%-10s -> [MRU] ", op)); for (DNode c = head.next; c != tail; c = c.next) sb.append(c.key).append(":").append(c.val).append(" "); System.out.println(sb.append("[LRU]")); } }
public static void main(String[] args) { TraceableLRU lru = new TraceableLRU(3); lru.put(1, 100); lru.put(2, 200); lru.put(3, 300); lru.get(1); lru.put(4, 400); }}put(1,100) -> [MRU] 1:100 [LRU] put(2,200) -> [MRU] 2:200 1:100 [LRU] put(3,300) -> [MRU] 3:300 2:200 1:100 [LRU] get(1) -> [MRU] 1:100 3:300 2:200 [LRU] put(4,400) -> [MRU] 4:400 1:100 3:300 [LRU]
What this code does
- Watch how
get(1)rescues1:100from the[LRU]end and promotes it to the[MRU]front. - Because
2:200is now at[LRU](tail.prev),put(4, 400)evicts2:200.
unlink(DNode node) sets node.prev.next = node.next; node.next.prev = node.prev;. addFirst(DNode node) places node between head and the old first node (head <-> node <-> oldFirst). Every get and put is a clean combination of these two helpers.
map.remove(lru.key) on eviction, or omitting int key from DNode.LinkedHashMap in the standard library
Java's standard library already includes a HashMap + Doubly Linked List class. java.util.LinkedHashMap<K, V> subclasses HashMap and links all of its entries into a doubly linked list.
Example 4 · Java Standard Library Equivalent: LinkedHashMap With accessOrder = true
import java.util.LinkedHashMap;import java.util.Map;
public class LinkedHashMapLRUDemo { static class StdLibLRUCache extends LinkedHashMap<Integer, Integer> { private final int capacity;
public StdLibLRUCache(int capacity) { // accessOrder = true moves accessed entries to the MRU end super(capacity, 0.75f, true); this.capacity = capacity; }
public int getVal(int key) { return super.getOrDefault(key, -1); }
@Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > capacity; } }
public static void main(String[] args) { StdLibLRUCache cache = new StdLibLRUCache(2); cache.put(1, 10); cache.put(2, 20); System.out.println("get(1): " + cache.getVal(1)); cache.put(3, 30); System.out.println("get(2): " + cache.getVal(2)); System.out.println("Remaining entries (LRU -> MRU): " + cache); }}get(1): 10
get(2): -1
Remaining entries (LRU -> MRU): {1=10, 3=30}What this code does
LinkedHashMapkeeps the least recently used entry at the head (eldest) and most recent at the tail.- Knowing both custom
DNode+HashMapandLinkedHashMap.removeEldestEntryis great for Java interviews.
By default, LinkedHashMap keeps insertion order. Passing accessOrder = true to new LinkedHashMap<>(capacity, 0.75f, true) switches it to LRU access order on every get or put. Overriding removeEldestEntry(Map.Entry<K, V> eldest) to return size() > capacity makes LinkedHashMap evict the oldest entry automatically.
When to use which:
- In interviews: Write
DNode+HashMapfrom scratch first, and mentionLinkedHashMapas a follow-up. - In production Java: Use
LinkedHashMap(cap, 0.75f, true)for single-threaded caches, or Caffeine for multi-threaded caches.
Next step
Check your understanding
10 quick questions