Learn the pattern · ~15 min
System / DS Design
also called LRU/LFU cache, class design
When one structure makes some operation slow, add a second structure that indexes exactly what that operation needs, and update every structure on every write.
Reach for it when you read
- +"Design a class" with named methods and a target cost for each, usually O(1) or O(log n).
- +Two needs that fight each other: find by key and keep an order (recency, frequency, time).
- +Delete an arbitrary item and pick a random one, both in O(1).
- +A stream of calls where each answer depends on everything so far: the latest value at time t, the current minimum.
- +An OA spec that grows in levels: records, then queries per field, then history or expiry.
Not this one when
- ×One query over a fixed array, asked once: solve it directly; no class or extra index is needed.
- ×Only the top k or the minimum of a changing set, nothing else: a single heap is the whole design.
- ×A running median: that's two heaps, its own pattern.
Learn System / DS Design
First, what is a "design" problem, and what is "LRU"?
A design problem asks for a class whose operations each have a target cost, usually O(1). The work is choosing structures so that every operation hits it.
Our example is an LRU cache: least recently used. Use keys 1, 2, 3, 1: the least recently used is now 2, whose last use is oldest. A full cache throws that one out.
The tool: a list you can cut in O(1)
A doubly linked list keeps items in order, each node pointing both ways: next to the node after, prev to the one before. Two fake nodes, H before the first item and T after the last, are sentinels: every real node always has neighbours on both sides.
The rule:
If you hold a pointer to a node, you can cut it out or put it at the front by changing a fixed number of pointers. No walking.
Take H ⇄ 1 ⇄ 3 ⇄ 2 ⇄ T and move 2 to the front:
| step | what happens | list (following next) |
|---|---|---|
| 1 | 3, before 2, now points forward to T, after 2 | H, 1, 3, T |
| 2 | T points back to 3: 2 is cut out | H, 1, 3, T |
| 3 | 2 points forward to the old first node, 1, and back to H | H, 1, 3, T |
| 4 | 1 points back to 2 | H, 1, 3, T |
| 5 | H points forward to 2 | H, 2, 1, 3, T |
Six pointer changes, whether the list has 3 nodes or 3 million.
The code for it
struct Node {
int key, val;
Node *prev = nullptr, *next = nullptr;
};
Node H, T; // sentinels (global: one live cache at a time)
void unlink(Node* x) { // cut x out: its two neighbours point at each other
x->prev->next = x->next;
x->next->prev = x->prev;
}
void pushFront(Node* x) { // put x right after H
x->next = H.next;
x->prev = &H;
H.next->prev = x;
H.next = x;
}You don't need to memorise this: unlink is steps 1–2, pushFront steps 3–5. Why prev? Cutting a node out means fixing the node before it, which a one-way list can only find by walking from the front. Why sentinels? Without them, the first and last node would each need their own if.
Fine, but how does this help us?
The classic problem, LRU Cache: build a cache with capacity cap:
get(key): its value, or −1 if absent.put(key, value): insert or update; if the size passescap, evict the least recently used key.
Both count as a use, and both must be O(1). By hand, capacity 3:
| call | returns | keys, most recent first | how you decided |
|---|---|---|---|
| put(1, 10) | 1 | ||
| put(2, 20) | 2, 1 | ||
| put(3, 30) | 3, 2, 1 | full now | |
| get(1) | 10 | 1, 3, 2 | 1 was just used: front |
| put(4, 40) | 4, 1, 3 | 4 keys > 3: evict the oldest, 2 | |
| get(2) | -1 | 4, 1, 3 | 2 is gone |
| put(3, 33) | 3, 4, 1 | an update is a use: 3 to the front | |
| put(5, 50) | 5, 3, 4 | over again: evict the oldest, 1 | |
| get(1) | -1 | 5, 3, 4 | 1 is gone |
| get(4) | 40 | 4, 5, 3 | 4 to the front |
The brute force
Keep the pairs in an array, most recent first. Each call scans for the key and shifts the others to put it first.
struct LRUBrute {
int cap;
vector<pair<int, int>> order; // (key, value), most recent first
LRUBrute(int c) : cap(c) {}
int get(int key) {
for (int i = 0; i < (int)order.size(); i++)
if (order[i].first == key) { // scan for the key...
auto kv = order[i];
order.erase(order.begin() + i);
order.insert(order.begin(), kv); // ...and shift everything to put it first
return kv.second;
}
return -1;
}
void put(int key, int value) {
for (auto& kv : order)
if (kv.first == key) { get(key); order[0].second = value; return; } // an update is a use
order.insert(order.begin(), {key, value});
if ((int)order.size() > cap) order.pop_back(); // the last one is the oldest
}
};It returns 10, -1, -1, 40, scanning and shifting up to cap elements per call. At LeetCode's limits (capacity 3,000, 2 × 10⁵ calls) that still passes in 0.3 s with -O2: a shift is one fast memory move. But it's O(cap) per call, not O(1): at capacity 10⁵ the same calls take 14 seconds.
The one thought that fixes it
Stop at get(1), the 4th call. The array is 3, 2, 1. The brute force scans past 3 and 2 to find 1, then shifts them one place right to make room in front.
The list removes the shifting: moving a node to the front is six pointer changes. But it can't find key 1 any faster; you'd still walk 3 and 2. The scan only answers where is key 1's node?
So store that answer: a hash map key → node pointer finds the node, and the list moves it:
| operation | hash map alone | list alone | both |
|---|---|---|---|
| find a key | O(1) | O(n) walk | O(1), via the map |
| mark it most recent | there's no order | O(1), if you hold the node | O(1) |
| evict the oldest | O(n) search | O(1): it's T.prev |
O(1) |
One catch: the two must always agree. An evicted node must leave the map too, which is why each node stores its key.
struct LRUCache {
int cap;
unordered_map<int, Node*> pos; // key -> its node in the list
LRUCache(int c) : cap(c) { H.next = &T; T.prev = &H; }
int get(int key) {
auto it = pos.find(key);
if (it == pos.end()) return -1;
Node* x = it->second; // found without a scan
unlink(x);
pushFront(x); // a read is a use: now the most recent
return x->val;
}
void put(int key, int value) {
if (pos.count(key)) { get(key); pos[key]->val = value; return; } // get() moves it to the front
Node* x = new Node{key, value};
pos[key] = x;
pushFront(x);
if ((int)pos.size() > cap) {
Node* old = T.prev; // the back is the least recently used
unlink(old);
pos.erase(old->key); // evict from BOTH structures
delete old;
}
}
};Dry run
Same calls. The map always holds exactly the list's keys.
| call | returns | list after (H → T) | map keys | evicted |
|---|---|---|---|---|
| put(1, 10) | 1:10 | 1 | ||
| put(2, 20) | 2:20, 1:10 | 1, 2 | ||
| put(3, 30) | 3:30, 2:20, 1:10 | 1, 2, 3 | ||
| get(1) | 10 | 1:10, 3:30, 2:20 | 1, 2, 3 | |
| put(4, 40) | 4:40, 1:10, 3:30 | 1, 3, 4 | 2 | |
| get(2) | -1 | 4:40, 1:10, 3:30 | 1, 3, 4 | |
| put(3, 33) | 3:33, 4:40, 1:10 | 1, 3, 4 | ||
| put(5, 50) | 5:50, 3:33, 4:40 | 3, 4, 5 | 1 | |
| get(1) | -1 | 5:50, 3:33, 4:40 | 3, 4, 5 | |
| get(4) | 40 | 4:40, 5:50, 3:33 | 3, 4, 5 |
10, -1, -1, 40, the same answer as the brute force.
Why it's O(1)
Each call does a few hash lookups, one unlink, one pushFront, maybe one eviction (an unlink and a map erase). None depends on how many keys are stored: O(1) per call, on average (hashing). Space is O(cap): one node and one map entry per key.
From a scan per call to none: store where each key lives.
Min Stack? Store extra data in each entry
push, pop, top, getMin, all O(1). The hard one is getMin, so each entry remembers the smallest value at or below it:
vector<pair<int, int>> st; // (value, smallest value at or below it)
void push(int x) { st.push_back({x, st.empty() ? x : min(x, st.back().second)}); }
int getMin() { return st.back().second; }Push 5, 2, 7, 1: getMin gives 5, 2, 2, 1. Pop the 1 and it's 2 again: the entry below knew.
Insert, Delete, GetRandom? A map and an array point at each other
A random pick needs an array. Deleting from its middle is slow, unless you move the last value into the hole; the map says where the hole is:
vector<int> vals; // the values, in any order
unordered_map<int, int> at; // value -> its index in vals
void removeVal(int x) {
int i = at[x], last = vals.back();
vals[i] = last; // move the last value into the hole
at[last] = i;
vals.pop_back();
at.erase(x);
}With 4 9 6 2, deleting 9 moves 2 into index 1: 4 2 6, and the map says 2 lives at 1.
Remember this
- Write each operation next to its target cost. The one your first structure makes slow tells you what to add.
- Every write updates every structure: forgetting the map on eviction is the classic LRU bug.
- Whenever a problem says "design a class" with O(1) per operation, look for two structures that index each other.
Practise it on Min Stack, then Insert Delete GetRandom O(1), Time Based Key-Value Store (per key, times in order and a binary search), LRU Cache and LFU Cache (a list of keys per use count, plus the smallest count).
Below, watch LRU Cache run line by line.
Watch it work, line by line
LRU Cache ↗, cap = 2: put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4) → 1 -1 -1 3 4. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Which operation is slow with one structure, and what index would make exactly that operation O(1)? Can I keep every index in sync on every write?
Reach for it when
- +'design a class with operations X, Y, Z in O(1)'
- +cache eviction policies
- +iterator / stream APIs
- +operation complexity targets stated
It fails when
- ×A single standard container already does the jobuse That container; don't over-engineer
- ×It's an algorithm question in disguise (graph/DP)use Solve the underlying algorithm
- ×Persistence or concurrency requirementsuse Out of scope for in-memory DS designs
- ×Requirements contradict (O(1) sorted iteration + O(1) arbitrary insert)use Point out the conflict; ask which op may relax
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1In LRU, what does each structure buy you?Reveal
The hash map finds a key in O(1). The doubly linked list moves a node to the front and evicts from the back in O(1).
2Why does each list node store its key?Reveal
Eviction starts from the list (
tail->prev). The node's key is how you erase it from the map.3What's the invariant every design question shares?Reveal
Every structure stays consistent with the others after every operation: same keys, correct indexes.
Practice ladder
- 1Implement Queue using Stacksamortised by batchesEasy
- 2Moving Average from Data Streama sliding window of timeEasy
- 3Min Stackextra data per entryMedium
- 4Insert Delete GetRandom O(1)map and arrayMedium
- 5Time Based Key-Value Storeversions over timeMedium
- 6LRU Cachethe hookMedium
- 7In-Memory Database (CodeSignal ICF, 4 levels)build it in levelsMedium
- 8Design Twittermaps plus a heap mergeMedium
- 9All O`one Data Structurefrequency bucketsHard
- 10LFU Cachethe bossHard
Finished System / DS Design? Mark it done and Lessgo moves you to the next step.