Lesson 39 of 40Strings, math and design
Design Problems: LRU Cache, Iterators and Friends
Build classes with an exact cost per method: LRU and LFU caches, min and max stacks, O(1) random sets, iterators and time-based stores.
A product page calls a pricing service so often that someone adds a small in-process cache, and a week later memory alarms fire because nothing is ever evicted. A paginated API returns a cursor, and a teammate's client code loads all ten million rows into a list before looping. A config service must answer "what was this value at 14:02 yesterday?" for an incident review. Each of these is a small class with three or four methods, and each method has a cost you must be able to state. Interviewers ask "design" problems because they test exactly that: you choose two or three structures that cooperate, and every method stays fast.
How design questions are graded
These problems hand you an API (get, put, next, has_next) and a target cost per method, often O(1). The grading is different from a normal algorithm question.
- The API is fixed and every method counts. A fast
getwith an O(n)putfails. Write the cost next to each method before you write code. - State your invariants. "The map holds exactly the keys in the list." "
min_freqis always the smallest count in use." Every method must leave those true. Most bugs are a method that forgets to update the second structure. - Composition is the trick. Almost every answer is a hash map plus something that keeps order: a linked list, an array, a stack, a deque or a sorted list. The map gives O(1) lookup; the other structure gives O(1) "oldest", "smallest" or "random".
- Test the edges out loud. Capacity 0 or 1, updating an existing key, removing the last element, an empty nested list, a timestamp before the first write.
LRU Cache
"Design a cache of fixed capacity. get(key) returns the value or -1. put(key, value) inserts or updates. When full, evict the least recently used key. Both in O(1)." This is the most asked design question there is.
The structure is a hash map plus a doubly linked list in recency order. The map finds a key's node in O(1). Because each node knows both neighbours, you can unlink it and move it to the front in O(1), and the least recently used key is always at the tail. Sentinel head and tail nodes remove the "is the list empty?" special cases. Design a Distributed Cache walks through that hand-rolled version line by line in its "Single node first" section, and you should be able to write it from memory. Here the focus is on the two ways interviews actually play out.
"You can use the standard library." Python's OrderedDict is that same map-plus-linked-list, written in C. move_to_end(key) marks a use and popitem(last=False) evicts the oldest. In JavaScript, a Map iterates in insertion order, so delete then set moves a key to the end, and map.keys().next().value is the oldest key. Both versions are short enough to finish with time left for questions.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Note the JavaScript detail: map.set on an existing key keeps its old position. That is why put deletes first. Forgetting it gives a cache where updates do not count as uses.
"Implement it without OrderedDict." Many interviewers say this, because the library version hides the part they want to see. Then write the linked list version, and talk about the invariant: every node in the list has an entry in the map and the other way round, so every eviction deletes from both. The random comparison against SlowLRU above is the same check you should run on your hand-rolled version. It catches the classic bugs: forgetting to move a key on update, and evicting before checking whether the key already exists.
At work, you would rarely write either. Python's functools.lru_cache covers function results, and a shared cache like Redis approximates LRU by sampling, as Design a Distributed Cache explains.
What does this print?
from collections import OrderedDict
cache, cap = OrderedDict(), 2
def get(k):
if k not in cache: return -1
cache.move_to_end(k); return cache[k]
def put(k, v):
if k in cache: cache.move_to_end(k)
cache[k] = v
if len(cache) > cap: cache.popitem(last=False)
put("a", 1); put("b", 2); get("a"); put("c", 3)
print(list(cache))LFU Cache: one more dimension
LFU evicts the key used least often, and among ties, the least recently used. It is a hard problem, and most interviewers accept a clear explanation plus code close to this.
Keep three maps: key -> value, key -> count, and count -> OrderedDict of keys (each bucket is a little LRU list). Plus one integer, min_freq, the smallest count currently in use. Two observations keep everything O(1):
- When a key is used, it moves from bucket
fto bucketf + 1. If bucketfbecomes empty andfwasmin_freq, then the new minimum is exactlyf + 1. No search needed. - A newly inserted key always has count 1, so after an insert
min_freqis 1.
Eviction pops the oldest key from bucket min_freq.
Press Run (⌘ Enter) to see what happens.Two traps: capacity 0 (every put must do nothing), and evicting before inserting the new key, since the new key has count 1 and would otherwise be evicted immediately.
Put the steps of LFU put(key, value) for a NEW key, with the cache full, in order.
- Tap the steps below in the right order.
Stacks that know their minimum
Min Stack: push, pop, top and get_min, all O(1). The trick is to store, with every entry, the minimum of the stack at the moment it was pushed. Popping then restores the previous minimum for free, because it is stored in the entry below. A second stack that only holds minimums works too, but you must push onto it on <=, not <, or duplicates of the minimum break it.
Max Stack adds pop_max, which removes the largest value from the middle of the stack. Now one structure cannot do both jobs. Keep a stack and a max-heap of the same entries, each tagged with a unique id, and use lazy deletion: when one structure removes an entry, record its id in a removed set, and the other structure skips that id the next time it looks at its top. Each entry is pushed and discarded once per structure, so the costs are O(log n) amortised for push, pop and pop_max.
heapq is a min-heap, so the code stores (-value, -id): the largest value comes out first, and among equal values the newest. Python 3.14 added public max-heap functions (heapq.heappush_max, heappop_max, heapify_max and friends), so on 3.14 you can skip the negation. Many interview platforms and production servers still run older versions, so know the negation trick and say which version you are assuming.
Press Run (⌘ Enter) to see what happens.Insert, Delete, GetRandom in O(1)
"A set with insert, remove and get_random, each O(1) on average, where get_random returns every element with equal probability." A hash set gives O(1) insert and remove but cannot pick a random element without walking it. An array gives O(1) random choice but O(n) removal from the middle. Use both: an array of values and a map from value to its index.
Removal is the clever part. Removing from the middle of an array shifts everything after it. So instead, copy the last element into the hole, update its index in the map, and pop the end, which is O(1).
The array holds the values. The map knows where each one lives.
The edge case: removing the element that is the last one. The code below copies it onto itself and then pops it, which works only if you update the map for last before deleting x from it. Do it in the other order and you re-insert the removed value into the map.
Press Run (⌘ Enter) to see what happens.Iterators: lazy by design
An iterator hands out one item at a time and remembers where it is. At work this is how you stream a ten-million-row export, page through an API, or read a log file without loading it all. In interviews it becomes a family of wrapper classes.
The two protocols. In Python, an iterator has __next__, which returns the next item or raises StopIteration, and __iter__, which returns itself. The built-in next(it, default) returns default instead of raising, which is the cleanest way to read ahead. A generator function (one with yield) builds an iterator for you and keeps its local variables paused between calls. In JavaScript, an iterator's next() returns { value, done }, and function* with yield is the generator equivalent.
Peeking Iterator adds peek() to an iterator that only has next. Read one item ahead and keep it in a buffer. Use a private sentinel object for "no more items", not None, because None can be a real value in the data.
Flatten Nested List Iterator turns [[1, [2]], [], 3] into 1, 2, 3. The naive answer flattens everything in the constructor. That works, but it is O(n) memory up front and defeats the point of an iterator. The expected answer keeps a stack of iterators and does the work lazily in has_next: pull from the top iterator, push a new iterator when you meet a list, pop when one runs out, and stop as soon as an integer is on top. The traps are empty lists ([[], [[]]] has no next item, so has_next must keep digging rather than return true on seeing a list) and callers who call next without has_next.
Zigzag Iterator alternates between lists. For k lists, keep a queue of (list, index) pairs: take from the front, and if that list still has items, put it at the back.
Press Run (⌘ Enter) to see what happens.The same ideas in JavaScript, where the protocol is an object with next() returning { value, done }:
Press Run (⌘ Enter) to see what happens.The JavaScript buffer holds the whole { value, done } result, so undefined as a real value is still distinguishable from the end. That is the same sentinel idea as _END in the Python version.
If the interviewer allows generators, say so: the recursive flatten generator is the cleanest answer. Then explain that the class version is what the generator does underneath, since a paused generator is a saved stack frame.
Time-indexed stores
A family of problems asks you to answer questions about the past. The shared trick: append each change with its time, so the list is sorted for free, then binary search.
Time Based Key-Value Store. set(key, value, t) and get(key, t) returning the value at the largest time <= t. Timestamps arrive in increasing order, so each key holds a list of times and a parallel list of values. get is bisect_right(times, t) - 1, as in Binary Search: the last position at or before t. If bisect_right returns 0, no value existed yet.
Design Hit Counter. hit(t) and get_hits(t) counting hits in the last 300 seconds. A deque of timestamps works: drop from the left while the oldest is out of the window. Each hit is appended and dropped once, so it is O(1) amortised. Compress repeated timestamps into (t, count) pairs to survive bursts. The follow-up "what if there are millions of hits per second?" leads to 300 circular buckets, one per second, each storing (timestamp, count): O(1) memory regardless of traffic, and the same idea as a sliding-window rate limiter.
Snapshot Array. set(i, v), snap() and get(i, snap_id). Copying the array on every snap is O(n) per snap. Instead, store for each index only the changes: a list of (snap_id, value). A get binary searches that index's list. Memory is proportional to the number of set calls, not snaps times length.
Press Run (⌘ Enter) to see what happens.Note that get_hits sums the deque, which is O(window) in the worst case. If that matters, keep a running total that you add to on hit and subtract from as entries leave.
Match each design problem to the structures it combines.
The senior follow-up: many threads
"Now many request threads call get and put at once. What changes?" This is a common senior follow-up to LRU, and the key insight is that get writes: it moves a node to the front. So a read-write lock, where many readers share access, does not help. Every operation mutates the list.
- One lock around every method. Simple and correct. In CPython the GIL does not save you: a single bytecode is atomic, but
move_to_endfollowed by a read is two steps, and another thread can run between them. - Striped locks (sharding). Split keys into N independent caches by
hash(key) % N, each with its own lock. Contention drops by roughly N. The cost is that eviction is per shard, so you get approximate global LRU. - Avoid exact LRU. Production caches such as Caffeine (Java) record accesses in a buffer and apply them in batches, or sample like Redis does. Mention that exact LRU order is a contention point, and that approximate recency usually gives nearly the same hit rate.
import threading
from collections import OrderedDict
class ThreadSafeLRU:
def __init__(self, capacity):
self.capacity = capacity
self.data = OrderedDict()
self.lock = threading.Lock()
def get(self, key, default=None):
with self.lock: # get mutates order, so it needs the lock too
if key not in self.data:
return default
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
with self.lock:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False)Design questions are where the whole course meets: a hash map, a linked list, a heap and an invariant inside one class. The wrap-up that follows takes that idea one step further and walks a single real task through every unit.
- invariant
- A fact every method must leave true, such as 'the map and the list hold the same keys'. Design bugs are usually a broken invariant.
- sentinel node
- A dummy head or tail node that is never removed, so list code never has to check for an empty list.
- lazy deletion
- Marking an entry as removed and skipping it later when it reaches the top, instead of deleting it from the middle of a heap or stack.
- iterator protocol
- Python:
__next__raisesStopIterationat the end. JavaScript:next()returns{ value, done }. - generator
- A function with
yieldthat returns an iterator and pauses between items, keeping its local state. - LFU
- Least frequently used eviction. Ties are broken by recency, and
min_freqtracks the smallest count in O(1). - lock striping
- Splitting shared state into shards with one lock each, so threads touching different keys do not wait on each other.