Design Data Structures · Lesson
Design data structures, explained: LRU cache, min stack and every pattern
Learn to design data structures: LRU cache, min stack, circular queue, O(1) random set and more, with class templates in Java, Python, C++ and JavaScript.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What a design problem asks
You get a class with a few methods, like get and put, and a target cost for each one. No single built-in structure does it all, so you combine two or three structures and keep them in sync.
Start by writing down every method and its target. Then ask, for each one: what would make this one fast? A hash map finds things, a linked list moves things, an array picks a random index, a heap finds the smallest. The answer is usually the union of those picks.
The trade-off: pay on write or pay on read
Most designs choose when to do the work. Pre-compute on every write (keep a running minimum, a count per row, a prefix sum) and reads become O(1). Or keep writes cheap and do the work when someone asks. Pick the side that is called more often.
- Find by key: hash map.
- Move to the front or remove from the middle in O(1): doubly linked list plus a map to its nodes.
- Undo the latest, or remember a value per level: stack.
- First in, first out, or a fixed-size window: queue or ring buffer.
- Smallest or earliest first: heap. Pick uniformly at random: array.
How to keep it correct
Bugs in design problems are almost always two structures that disagree: the map still points to a node you removed, or a heap holds an entry for a key that changed. Every method that touches one structure must update the others too.
Test the edges on paper before coding: the structure is empty, it is full (capacity 1 is a good test), and the same key is used twice in a row.
What it costs
| Operation | Time | Space |
|---|---|---|
| LRU cache get / put (map + doubly linked list) | O(1) | O(capacity) |
| Min stack push / pop / getMin | O(1) | O(n) |
| Circular queue enqueue / dequeue | O(1) | O(k) |
| Insert / delete / getRandom (map + array) | O(1) average | O(n) |
| Range sum with updates (Fenwick tree) | O(log n) each | O(n) |
| Expiring cache with a min-heap | O(log n) amortised | O(n) |
Built into your language
Map<Integer, Integer> lru = new LinkedHashMap<>(16, 0.75f, true) { // access order
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> e) { return size() > 2; }
};
Deque<Integer> dq = new ArrayDeque<>(); // stack or queue: push/pop, offerLast/pollFirst
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
TreeMap<Integer, Integer> tm = new TreeMap<>(); // sorted keys: firstKey(), floorKey(x)
new Random().nextInt(n); // 0 .. n - 1 from collections import OrderedDict, deque
import heapq, random
od = OrderedDict()
od[1] = 'a'; od.move_to_end(1) # mark as most recent
od.popitem(last=False) # remove the oldest
window = deque(maxlen=3) # a ring buffer: old items fall off
heapq.heappush(h := [], (5, 'k')); heapq.heappop(h)
random.randrange(n) # 0 .. n - 1 list<int> items; // doubly linked list
items.splice(items.begin(), items, it); // move node it to the front in O(1)
unordered_map<int, list<int>::iterator> where;
deque<int> dq; // push_back / pop_front
priority_queue<int, vector<int>, greater<int>> minHeap;
mt19937 rng(random_device{}());
uniform_int_distribution<int>(0, n - 1)(rng); const m = new Map(); // keeps insertion order
m.delete(k); m.set(k, v); // re-insert: k becomes the newest
m.keys().next().value; // the oldest key
const st = []; // stack: push / pop
// no built-in queue or heap: use an array with a head index, or write a small heap
Math.floor(Math.random() * n); // 0 .. n - 1 Mistakes everyone makes
- Updating one structure and forgetting the other: removing a node from the list but not its key from the map.
- Hiding an O(n) step in an O(1) method:
list.remove(value)in Java,shift()in JavaScript,pop(0)in Python. - Not handling the empty case:
top,getMin,Frontordequeueon an empty structure. - Off-by-one on capacity: evicting after inserting instead of before, so the structure briefly holds one too many.
- Returning the internal array (in reset or shuffle) so the caller can change your state: return a copy.
The 10 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Pre-processing and trade-offs: pay on write or on read Decide which method should be fast, and do the work in the other one. Index the data when the class is built, keep counters up to date on every write, or use a tree that makes both sides O(log n). 6 variations · 14 problems
- 2 Linked list designs: LRU cache and friends A doubly linked list can move or remove any node in O(1) if you already hold it, and a hash map from key to node gives you that node. Together they make an LRU cache, and with buckets per count, LFU and All O'one. 3 variations · 5 problems
- 3 Stack designs: min stack, frequency stack, text editor A stack can remember extra facts about everything below each item, like the minimum so far. Store that fact with the item when you push, and it is still correct when you pop back to it. 5 variations · 7 problems
- 4 Queues and ring buffers: fixed windows and streams A queue serves items in arrival order. With a fixed capacity, an array plus a head index and a size wraps around with
% k, so nothing ever shifts. Queues also keep "the last N items" or "the last 300 seconds" of a stream. 3 variations · 6 problems - 5 Hash map + array: O(1) insert, delete and random An array can return a random element in O(1) but cannot delete from the middle. A hash map from value to index fixes that: move the last element into the hole, update its index, then pop the end. 2 variations · 4 problems
- 6 Hash map + heap: expiring keys in time order The map holds the current value and expiry of each key; a min-heap holds expiry times, so the next key to expire is always on top. Before each call, pop everything that has expired. 2 variations · 2 problems
- 7 Randomized algorithms: a fair shuffle Fisher-Yates walks from the end and swaps each position with a random position at or before it. Every one of the n! orders comes out with the same chance, in O(n). 2 variations · 2 problems
- 8 Dependency graphs: formulas that update A formula cell depends on other cells, which may depend on more. Store each formula as the cells it adds (with counts), and compute a cell by following those edges, so a change anywhere always shows up. 1 variation · 1 problem
- 9 Concurrency: a bounded blocking queue Producers wait while the queue is full and consumers wait while it is empty. One lock protects the queue, and a condition variable lets a thread sleep until another one changes the state. 1 variation · 1 problem
- 10 Simulation designs: model the state directly When the limits are small, the simplest correct design is to store the state exactly as described and scan it. A memory of n cells is an array of owner ids, and each call walks it once. 1 variation · 1 problem