An LRU (least recently used) cache holds a fixed number of entries and, when full, evicts the entry that has gone unused the longest. The classic design pairs a hash map (find any entry in O(1)) with a doubly linked list (reorder and evict in O(1)), so both get and put run in constant time. It is one of the most frequently asked design questions in interviews, and the same building blocks extend to LFU (least frequently used) caches and the eviction policies behind real systems like Redis and CPU caches.
Think of it like
A small desk and a big bookshelf
Your desk fits five books. Whenever you use a book, you put it on top of the pile. When you need a sixth book, the one at the bottom of the pile, untouched for the longest, goes back to the shelf. The pile order is the linked list, and your memory of where each book sits in the pile is the hash map.
The problem
Design a structure with a fixed capacity that supports get(key) (return the value or −1, and mark the key as recently used) and put(key, value) (insert or update, mark as recently used, and evict the least recently used key if the cache is over capacity). Both operations must run in O(1) time.
Why one structure is not enough
| Structure | get | put / evict | Problem |
|---|---|---|---|
| Hash map with timestamps | O(1) | O(n) | Eviction must scan for the oldest timestamp |
| Array or singly linked list in recency order | O(n) | O(n) | Finding a key and moving it to the front are both linear |
| Min-heap keyed by last access | O(log n) | O(log n) | Every access updates a heap position |
| Balanced BST keyed by last access | O(log n) | O(log n) | Same: ordered but not constant time |
| Hash map + doubly linked list | O(1) | O(1) | Map finds the node, list reorders and evicts it |
The design: hash map + doubly linked list
The list keeps entries in recency order: the node right after the head is the most recently used (MRU), and the node right before the tail is the least recently used (LRU). The map stores key → node, so any entry can be found in O(1) and then unlinked and relinked in O(1).
map: { A -> nodeA, B -> nodeB, C -> nodeC }
head <-> [A] <-> [C] <-> [B] <-> tail
MRU LRU (next eviction)- Sentinel head and tail
- Dummy nodes that are always present. Every real node has a non-null
prevandnext, so insert and remove need no special cases for an empty list or the ends. - Node
- Stores
key,value,prevandnext. The key is needed so that evicting the LRU node can also delete it from the map. - Move to front
- Unlink a node from its current position and insert it right after the head. Done on every hit.
- 1
get(key)
Look up the node in the map. If missing, return −1. Otherwise move it to the front and return its value.
- 2
put(key, value), existing key
Update the node's value and move it to the front.
- 3
put(key, value), new key
Create a node, insert it right after the head, and add it to the map.
- 4
Evict if over capacity
The LRU node is
tail.prev. Unlink it and deletenode.keyfrom the map.
| Operation | Result | List after (MRU → LRU) | Note |
|---|---|---|---|
| put(1, 1) | 1 | ||
| put(2, 2) | 2, 1 | ||
| get(1) | 1 | 1, 2 | 1 becomes most recent |
| put(3, 3) | 3, 1 | Over capacity: evict 2 | |
| get(2) | −1 | 3, 1 | Miss |
| put(4, 4) | 4, 3 | Evict 1 | |
| get(1) | −1 | 4, 3 | Miss |
| get(3) | 3 | 3, 4 | |
| get(4) | 4 | 4, 3 |
Using built-ins
Many languages ship an insertion-ordered hash map, which is exactly a hash map threaded with a linked list:
- Python:
collections.OrderedDictwithmove_to_end(key)on access andpopitem(last=False)to evict.functools.lru_cachememoizes functions with the same policy. - Java:
LinkedHashMapconstructed withaccessOrder = true, overridingremoveEldestEntryto returnsize() > capacity. - JavaScript / TypeScript:
Mapiterates in insertion order. Refresh a key withdeletethenset, and evictmap.keys().next().value. - C++:
std::listplusstd::unordered_map<Key, std::list<...>::iterator>, usingspliceto move a node to the front in O(1).
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data: OrderedDict[int, int] = OrderedDict()
def get(self, key: int) -> int:
if key not in self.data:
return -1
self.data.move_to_end(key) # most recent at the end
return self.data[key]
def put(self, key: int, value: int) -> None:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False) # evict the least recent (front)LFU: evicting the least frequently used
An LFU cache evicts the key with the smallest access count, breaking ties by evicting the least recently used among them. A heap keyed by frequency would make every access O(log n). The O(1) design groups keys into frequency buckets, each an LRU-ordered list, and tracks the smallest non-empty frequency in minFreq.
- keyToEntry
- Map from key to its value and current frequency.
- freqToKeys
- Map from frequency to an insertion-ordered set (or doubly linked list) of keys with that frequency, oldest first.
- minFreq
- The smallest frequency that currently has at least one key. Eviction always comes from this bucket.
- 1
Touch (on get or update)
Remove the key from bucket
fand append it to bucketf + 1. If bucketfis now empty andf == minFreq, incrementminFreq. - 2
Insert a new key
If the cache is full, evict the oldest key in bucket
minFreq. Then add the new key to bucket 1 and setminFreq = 1.
| Operation | Result | Frequencies after | Note |
|---|---|---|---|
| put(1, 1) | 1: f1 | minFreq = 1 | |
| put(2, 2) | 1: f1, 2: f1 | ||
| get(1) | 1 | 1: f2, 2: f1 | |
| put(3, 3) | 1: f2, 3: f1 | Full: evict key 2 (frequency 1) | |
| get(2) | −1 | Miss | |
| get(3) | 3 | 1: f2, 3: f2 | minFreq becomes 2 |
| put(4, 4) | 3: f2, 4: f1 | Tie at frequency 2: evict key 1, the least recently used | |
| get(1), get(3), get(4) | −1, 3, 4 |
Other eviction policies
| Policy | Evicts | Strengths | Weaknesses / where used |
|---|---|---|---|
| FIFO | The oldest inserted entry | Trivial, no work on hits | Ignores reuse; can show Belady's anomaly (more memory, more misses) |
| LRU | The least recently used entry | Great for temporal locality | A single large scan flushes the hot set |
| LFU | The least frequently used entry | Keeps long-term favorites | Slow to adapt; old popular keys linger without aging |
| CLOCK (second chance) | Approximate LRU using a reference bit and a circular pointer | Cheap on hits, no list reordering | Operating system page replacement |
| ARC | Balances recency and frequency with two LRU lists plus "ghost" lists of recent evictions | Self-tuning and scan resistant | Used in ZFS |
| W-TinyLFU | Admits a newcomer only if its estimated frequency beats the victim's | Near-optimal hit rates with tiny metadata (count-min sketch) | Java's Caffeine cache |
| Random | A random entry | No bookkeeping | Surprisingly decent for large caches; some CPU caches |
Production concerns
- Thread safety: a single lock around get and put is correct but serializes every hit, because even a read reorders the list. Production caches shard the cache by key hash or record hits in buffers and replay them asynchronously (Caffeine).
- Scan resistance: one sequential scan of a large table can evict the entire working set from a plain LRU. Segmented LRU (probation and protected segments), 2Q and ARC defend against it.
- Size by bytes: real caches limit memory, not entry count, so eviction loops until enough bytes are free.
- Expiry: TTLs need either lazy checks on access or a background sweeper.
- Metrics: track hit ratio, eviction rate and latency; a cache is only as good as its hit rate.
LRU
- Assumes recently used means soon used again
- Hash map + one doubly linked list
- Adapts instantly to shifting workloads
- Vulnerable to scans
LFU
- Assumes frequently used means soon used again
- Hash map + frequency buckets + minFreq
- Keeps stable hot keys through bursts and scans
- Needs aging, or yesterday's hits block today's
Complexity
| Operation | LRU | LFU | Notes |
|---|---|---|---|
| get | O(1) | O(1) | Map lookup plus list move (LRU) or bucket move (LFU) |
| put (update) | O(1) | O(1) | Same as a hit |
| put (insert + evict) | O(1) | O(1) | Evict tail.prev (LRU) or the oldest key in bucket minFreq (LFU) |
| Space | O(capacity) | O(capacity) | One node and one map entry per key |
Hash map operations are O(1) on average.
Implementation
Hand-built list in Python, TypeScript and Java. The C++ version uses `std::list` (itself a doubly linked list with a sentinel) and `splice` to move nodes in O(1).
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key: int = 0, value: int = 0):
self.key, self.value = key, value
self.prev: "Node | None" = None
self.next: "Node | None" = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map: dict[int, Node] = {}
self.head, self.tail = Node(), Node() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, node: Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def _add_to_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:
node = self.map.get(key)
if node is None:
return -1
self._remove(node) # mark as most recently used
self._add_to_front(node)
return node.value
def put(self, key: int, value: int) -> None:
node = self.map.get(key)
if node is not None:
node.value = value
self._remove(node)
self._add_to_front(node)
return
node = Node(key, value)
self.map[key] = node
self._add_to_front(node)
if len(self.map) > self.capacity:
lru = self.tail.prev # least recently used
self._remove(lru)
del self.map[lru.key] # why the node stores its keyKey takeaways
- LRU = hash map (find the node in O(1)) + doubly linked list (reorder and evict in O(1)).
- Sentinel head and tail nodes remove every edge case from insert and remove.
- Nodes store their key so the evicted tail can be deleted from the map.
- LFU groups keys into per-frequency LRU buckets and tracks
minFreq, which only resets to 1 or increments by 1. - Real systems approximate (Redis sampling, CLOCK) or use smarter policies (ARC, W-TinyLFU) for scan resistance and lower overhead.
Common pitfalls
- Using a singly linked list, which makes removing an arbitrary node O(n).
- Forgetting to move a node to the front on
get, or onputof an existing key. - Evicting before inserting when the key already exists, which evicts an entry unnecessarily.
- Not storing the key in the node, leaving no O(1) way to delete the evicted entry from the map.
- In LFU, forgetting to reset
minFreqto 1 after inserting a new key.
Interview tips
- Start by explaining why neither a hash map nor a list alone achieves O(1), then combine them.
- Write
removeandaddToFronthelpers first; everything else is three or four lines. - Be ready for follow-ups: thread safety (locks, sharding), TTL expiry, and LFU with the minFreq argument.
Real-world applications
- In-memory caches in front of databases and APIs (Memcached and Redis eviction).
- Operating system page replacement (CLOCK approximations of LRU).
- CPU and disk buffer caches, database buffer pools.
- Browser caches and function memoization (
functools.lru_cache).
Practice problems
Test yourself
Why does an O(1) LRU cache use a doubly linked list?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.