Design a data structure (LRU cache)
In a "design a class" round no single structure makes every operation O(1), so you compose two: a hash map to find things plus a list, linked list or stack that keeps the order.
Analogy: A library: the catalog tells you the shelf instantly, the shelf order tells you which book is oldest. You need both, and every loan must update both.
How it works
- List what each operation needs, pick one structure per need, and keep them in sync.
- LRU cache = hash map (key → node) + doubly linked list in recency order.
getmoves the node to the front;putevicts the tail when over capacity.- Min stack: every entry stores the minimum so far, so a pop restores it.
- getRandom in O(1): array plus value → index map; delete by swapping with the last element.
Check yourself
Answer to mark it learned; your answers aren't scored.
Design a set with insert, remove and getRandom (uniform), all O(1). A hash set already gives O(1) insert and remove. How do you add getRandom?
Go deeper
Solve it in Python 10
- Queue built from two stackseasy
- Rate limiter over a sliding windoweasy
- Stack that knows its minimumeasy
- Cache that evicts the stalest keymedium
- Feed of the newest postsmedium
- Set with O(1) removal and indexingmedium
- Price tracker with late correctionsmedium
- Tic-tac-toe referee in O(1) per movemedium
- Cache that evicts the least-used keyhard
- Stack that pops the most frequent valuehard
Full explanation
The prompt gives an API and a cost, usually "every operation in O(1)". No single structure does it, so you compose two and keep them in sync on every write.
Start from what each operation needs: lookup by key → hash map; recency or insertion order → linked list; pick by index → array; running min or max → an extra stack.
- LRU cache: a hash map from key to node, plus a doubly linked list in recency order.
getmoves the node to the front;putinserts at the front and, over capacity, evicts the tail. The map hands you the node and a doubly linked node can unlink itself, so each step is O(1). Python'sOrderedDictpackages this pair. - Min stack: each entry stores
(value, min so far), so popping restores the previous minimum. - Insert/delete/getRandom: an array for O(1) random picks plus a map from value to index. To delete, move the last element into the hole and pop the end.
Say the invariant out loud ("map and list hold the same keys") before you code.
Code LRU cache with OrderedDict, and an O(1) random set
import random
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap, self.data = capacity, OrderedDict() # hash map + doubly linked list
def get(self, key):
if key in self.data:
self.data.move_to_end(key) # a read also counts as a use
return self.data.get(key, -1)
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key) # also when overwriting a key
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict the least recently used
class RandomizedSet:
def __init__(self):
self.items, self.pos = [], {} # array to pick from, value -> index
def insert(self, x):
if x not in self.pos:
self.pos[x] = len(self.items)
self.items.append(x)
def remove(self, x):
if x in self.pos:
i, last = self.pos.pop(x), self.items.pop()
if i < len(self.items): # x wasn't last: fill its hole
self.items[i], self.pos[last] = last, i
def get_random(self):
return random.choice(self.items) # uniform, O(1)Real example
LRU cache with capacity 2. put(1, A), put(2, B) → recency order [2, 1]. get(1) returns A and moves key 1 to the front: [1, 2]. put(3, C) exceeds the capacity, so the tail, key 2, is evicted: [3, 1]. get(2) is now a miss. Each step is one map lookup plus a few pointer changes. A dict with a last-used timestamp per key would scan all n entries on every eviction: O(n).
Trade-offs +3 · −3
+ You gain
- Every operation is O(1) by construction.
- Reuses structures you already know; the work is the invariant, not a new algorithm.
- Maps to real components: caches, rate limiters, schedulers.
− You pay
- Two structures to update on every write: miss one and they drift apart.
- More memory per entry: a map entry plus a node with two pointers.
- Not thread-safe as written; a shared cache needs a lock or shards.
Use it when
The prompt is an API with a cost per operation: LRU or LFU cache, min/max stack, random set, hit counter, time-based key-value store. Also when a simple class has one O(n) operation to remove.
Avoid it when
One built-in already fits (a heap for "smallest next", deque for a queue), or the limits allow O(log n) or O(n): don't build a linked list you don't need.
Numbers to know 5
- LRU cache:
getandputin O(1) average; space O(capacity). - Min stack: push, pop, top and getMin in O(1); O(n) extra space for the stored minimums.
- Random set: insert, remove and getRandom in O(1) average (hash map).
- Python's
functools.lru_cachedefaults tomaxsize=128. - Redis approximates LRU by sampling keys (
maxmemory-samples, default 5): a true LRU costs more memory.
Common pitfalls 4
- LRU: forgetting that
getis also a use and must move the node. - LRU nodes that don't store the key: on eviction you can't delete the map entry.
- Min stack with one
minvariable: after popping the minimum, the previous one is lost. - Random set: not updating the moved element's index after the swap.
Interview questions 3
Answer out loud first, then reveal.
How do you approach a "design a class" question?Show answer
I write the API first, with the target cost next to each method. For each operation I name the structure that makes it O(1): a hash map for lookup, an array for index or random access, a linked list for reordering, a stack or heap for min and max. Then I state the invariant that ties them together and which methods must update both. Only then do I code, and I test the smallest capacity.
Implement an LRU cache without `OrderedDict`.Show answer
A dict from key to node, and a doubly linked list with two sentinel nodes, head and tail, so there are no null checks. Two helpers, remove(node) and add_front(node), both O(1). get is remove plus add_front. put updates or creates the node, moves it to the front and, if over capacity, removes tail.prev and deletes its key from the dict, which is why every node stores its key.
Make the LRU cache safe for many threads.Show answer
The simplest correct version is one lock around get and put; get writes too, because it reorders the list. If that lock gets hot, I shard by key hash, each shard with its own lock and list. Beyond that I'd question exact LRU: Redis samples a few keys instead of keeping a global list, because exact recency costs memory. For TTLs and stampedes, see Caching strategies.