Skip to lesson

Design an LRU cache

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)

SlowLruDemo.javaJava
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));    }}
Output
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: every get and put costs O(n).
  • The HashMap plus 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)

LRUCacheDemo.javaJava
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));    }}
Output
get(1): 10
get(2): -1
get(1): -1
get(3): 30
get(4): 40

What this code does

  • Calling cache.get(1) moves key 1 to head.next, leaving key 2 as the LRU entry at tail.prev.
  • When cache.put(3, 30) exceeds capacity 2, tail.prev (key 2) is unlinked and removed from map in 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>: maps key -> DNode in O(1) time so we never scan the linked list.
  • Doubly Linked List (head <-> ... <-> tail): orders MRU at head.next down to LRU at tail.prev.
  • Why each DNode stores both key and val: When evicting DNode lru = tail.prev, we need lru.key to call map.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.

  1. get(key): Look up DNode node = map.get(key). If node == null, return -1; otherwise call unlink(node); addFirst(node); and return node.val.
  2. put(key, value) when key exists: Look up DNode node = map.get(key), update node.val = value, and call unlink(node); addFirst(node);.
  3. put(key, value) when key is new: Create DNode node = new DNode(key, value), put (key, node) into map, and call addFirst(node). If map.size() > capacity, evict DNode lru = tail.prev via unlink(lru) and map.remove(lru.key).

Example 3 · Tracing the MRU-to-LRU Chain After Every Operation

LRUCacheTraceDemo.javaJava
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);    }}
Output
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) rescues 1:100 from the [LRU] end and promotes it to the [MRU] front.
  • Because 2:200 is now at [LRU] (tail.prev), put(4, 400) evicts 2: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.

A classic LRU bug is forgetting 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

LinkedHashMapLRUDemo.javaJava
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);    }}
Output
get(1): 10
get(2): -1
Remaining entries (LRU -> MRU): {1=10, 3=30}

What this code does

  • LinkedHashMap keeps the least recently used entry at the head (eldest) and most recent at the tail.
  • Knowing both custom DNode + HashMap and LinkedHashMap.removeEldestEntry is 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 + HashMap from scratch first, and mention LinkedHashMap as 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