Designing an LRU Cache
Combine a hash map and a doubly linked list for O(1) get and put — the most-asked data-structure design question.
A cache keeps a limited number of items in fast storage. When it's full, it must evict something. LRU (Least Recently Used) evicts the item that hasn't been accessed for the longest time — betting that recently used data will be used again soon (temporal locality).
The requirement: get(key) and put(key, value) both in O(1).
Why two structures
- A hash map gives O(1) lookup by key — but has no notion of order.
- A doubly linked list keeps items in recency order and can move or remove any node in O(1) — if you already hold a pointer to that node.
So: the map stores key → node, and the list orders nodes from most to least recently used.
| Operation | Steps | Cost |
|---|---|---|
get(k) | Look up node in map; move it to the front; return value | O(1) |
put(k, v) existing | Update value; move to front | O(1) |
put(k, v) new | Create node at front, add to map; if over capacity remove the tail node and its map entry | O(1) |
class LRUCache {
private static class Node {
int key, val;
Node prev, next;
Node(int k, int v) { key = k; val = v; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0), tail = new Node(0, 0);
LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
Node n = map.get(key);
if (n == null) return -1;
remove(n);
addFront(n);
return n.val;
}
public void put(int key, int value) {
Node n = map.get(key);
if (n != null) {
n.val = value;
remove(n);
addFront(n);
return;
}
if (map.size() == capacity) {
Node lru = tail.prev;
remove(lru);
map.remove(lru.key); // why nodes store their key
}
n = new Node(key, value);
addFront(n);
map.put(key, n);
}
private void remove(Node n) {
n.prev.next = n.next;
n.next.prev = n.prev;
}
private void addFront(Node n) {
n.next = head.next;
n.prev = head;
head.next.prev = n;
head.next = n;
}
}
// Production shortcut: LinkedHashMap in access order
class LRU<K, V> extends LinkedHashMap<K, V> {
private final int cap;
LRU(int cap) { super(16, 0.75f, true); this.cap = cap; }
@Override protected boolean removeEldestEntry(Map.Entry<K, V> e) { return size() > cap; }
}class Node:
__slots__ = ("key", "val", "prev", "next")
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.cap = capacity
self.map = {}
self.head, self.tail = Node(), Node()
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _add_front(self, n):
n.prev, n.next = self.head, self.head.next
self.head.next.prev = n
self.head.next = n
def get(self, key: int) -> int:
n = self.map.get(key)
if not n:
return -1
self._remove(n)
self._add_front(n)
return n.val
def put(self, key: int, value: int) -> None:
if key in self.map:
n = self.map[key]
n.val = value
self._remove(n)
self._add_front(n)
return
if len(self.map) == self.cap:
lru = self.tail.prev
self._remove(lru)
del self.map[lru.key]
n = Node(key, value)
self._add_front(n)
self.map[key] = n
# Production shortcut:
from collections import OrderedDict
class LRU(OrderedDict):
def __init__(self, cap): super().__init__(); self.cap = cap
def get(self, k):
if k not in self: return -1
self.move_to_end(k); return self[k]
def put(self, k, v):
self[k] = v; self.move_to_end(k)
if len(self) > self.cap: self.popitem(last=False)
# Or simply decorate a function with @functools.lru_cache(maxsize=128)// A JS Map iterates in insertion order — re-inserting a key moves it to the end.
class LRUCache<K, V> {
private map = new Map<K, V>();
constructor(private capacity: number) {}
get(key: K): V | undefined {
if (!this.map.has(key)) return undefined;
const v = this.map.get(key)!;
this.map.delete(key); // move to most-recent position
this.map.set(key, v);
return v;
}
put(key: K, value: V) {
this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.capacity) {
const oldest = this.map.keys().next().value as K; // least recently used
this.map.delete(oldest);
}
}
}
// In an interview you may be asked to build the linked list by hand —
// the structure is identical to the Java version.Other eviction policies
| Policy | Evicts | Notes |
|---|---|---|
| LRU | Least recently used | Good default; fooled by one-time scans |
| LFU | Least frequently used | Keeps popular items; O(1) with frequency buckets |
| FIFO | Oldest inserted | Simple; ignores access pattern |
| Random | Random entry | Surprisingly decent, zero bookkeeping |
| TTL | Expired entries | Time-based; combined with others |
| W-TinyLFU | Admission + LRU | Caffeine (Java); near-optimal hit rates |
Redis offers allkeys-lru, allkeys-lfu, volatile-ttl and others — and approximates LRU by sampling a few keys rather than maintaining a global list. Operating systems approximate LRU for page replacement with the clock algorithm (Page replacement).
- LRU = hash map (find node in O(1)) + doubly linked list (reorder/evict in O(1)).
- Store the key in each node so you can delete the evicted node's map entry.
- Sentinel head/tail nodes remove edge cases.
- Know the library shortcuts:
LinkedHashMap,OrderedDict, JSMapordering.
QHow would you make the LRU cache thread-safe?medium
Simplest: one lock around get/put (both mutate the list, even get). For higher throughput, shard the cache into N independent LRUs by key hash, each with its own lock, or use a concurrent design like Caffeine that buffers access events and applies them in batches.
QDesign an LFU cache with O(1) operations.hard
Keep key → node and frequency → doubly linked list of nodes (each list in LRU order), plus minFreq. On access, move the node from list f to list f+1 and update minFreq if list f became empty. Evict from the tail of the minFreq list. New keys start at frequency 1 and set minFreq = 1.