Skip to content

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.

20 min read0/4 questions

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 get with an O(n) put fails. Write the cost next to each method before you write code.
  • State your invariants. "The map holds exactly the keys in the list." "min_freq is 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.

Python
import randomfrom collections import OrderedDict class LRUCache: """LeetCode signature: get returns -1 on a miss.""" def __init__(self, capacity): self.capacity = capacity self.data = OrderedDict() # oldest first, newest last def get(self, key): if key not in self.data: return -1 self.data.move_to_end(key) # a read counts as a use return self.data[key] def put(self, key, value): if key in self.data: self.data.move_to_end(key) # an update counts as a use too self.data[key] = value if len(self.data) > self.capacity: self.data.popitem(last=False) # evict the least recently used class SlowLRU: """Obviously correct reference: a list in recency order, O(n) per call.""" def __init__(self, capacity): self.capacity, self.items = capacity, [] # [(key, value)], newest last def get(self, key): for i, (k, v) in enumerate(self.items): if k == key: self.items.append(self.items.pop(i)) return v return -1 def put(self, key, value): self.items = [(k, v) for k, v in self.items if k != key] self.items.append((key, value)) if len(self.items) > self.capacity: self.items.pop(0) c = LRUCache(2)c.put(1, 1); c.put(2, 2)assert c.get(1) == 1 # 1 is now newestc.put(3, 3) # evicts 2assert c.get(2) == -1c.put(1, 10) # update moves 1 to newestc.put(4, 4) # evicts 3, not 1assert c.get(3) == -1 and c.get(1) == 10 and c.get(4) == 4 random.seed(3)for _ in range(200): cap = random.randint(1, 4) fast, slow = LRUCache(cap), SlowLRU(cap) for _ in range(60): k = random.randint(0, 6) if random.random() < 0.5: assert fast.get(k) == slow.get(k) else: v = random.randint(0, 99) fast.put(k, v); slow.put(k, v)print("LRU matches the reference on 200 random scripts")
Output
Press Run (⌘ Enter) to see what happens.
JavaScript
class LRUCache { constructor(capacity) { this.capacity = capacity; this.map = new Map(); // iterates in insertion order: oldest first } get(key) { if (!this.map.has(key)) return -1; const value = this.map.get(key); this.map.delete(key); // re-insert to move it to the end this.map.set(key, value); return value; } put(key, value) { this.map.delete(key); // so an update also moves it to the end this.map.set(key, value); if (this.map.size > this.capacity) { const oldest = this.map.keys().next().value; this.map.delete(oldest); } }} const c = new LRUCache(2);c.put(1, 1); c.put(2, 2);console.log(c.get(1)); // 1c.put(3, 3); // evicts 2console.log(c.get(2)); // -1console.log([...c.map.keys()]); // [ 1, 3 ]
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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 f to bucket f + 1. If bucket f becomes empty and f was min_freq, then the new minimum is exactly f + 1. No search needed.
  • A newly inserted key always has count 1, so after an insert min_freq is 1.

Eviction pops the oldest key from bucket min_freq.

Python
import randomfrom collections import defaultdict, OrderedDict class LFUCache: """Evict the least frequently used key; break ties by least recently used.""" def __init__(self, capacity): self.capacity = capacity self.vals = {} # key -> value self.freq = {} # key -> use count self.buckets = defaultdict(OrderedDict) # count -> keys, oldest first self.min_freq = 0 def _touch(self, key): f = self.freq[key] del self.buckets[f][key] if not self.buckets[f]: del self.buckets[f] if self.min_freq == f: self.min_freq = f + 1 # key moved up, so min moves with it self.freq[key] = f + 1 self.buckets[f + 1][key] = None def get(self, key): if key not in self.vals: return -1 self._touch(key) return self.vals[key] def put(self, key, value): if self.capacity == 0: return if key in self.vals: self.vals[key] = value self._touch(key) return if len(self.vals) == self.capacity: old, _ = self.buckets[self.min_freq].popitem(last=False) if not self.buckets[self.min_freq]: del self.buckets[self.min_freq] del self.vals[old], self.freq[old] self.vals[key], self.freq[key] = value, 1 self.buckets[1][key] = None self.min_freq = 1 # a brand-new key is always the minimum class SlowLFU: def __init__(self, capacity): self.capacity, self.vals, self.freq, self.last, self.t = capacity, {}, {}, {}, 0 def _use(self, key): self.t += 1 self.freq[key] = self.freq.get(key, 0) + 1 self.last[key] = self.t def get(self, key): if key not in self.vals: return -1 self._use(key) return self.vals[key] def put(self, key, value): if self.capacity == 0: return if key not in self.vals and len(self.vals) == self.capacity: victim = min(self.vals, key=lambda k: (self.freq[k], self.last[k])) del self.vals[victim], self.freq[victim], self.last[victim] self.vals[key] = value self._use(key) c = LFUCache(2)c.put(1, 1); c.put(2, 2)assert c.get(1) == 1 # key 1 used twice, key 2 oncec.put(3, 3) # evicts 2 (lowest count)assert c.get(2) == -1assert c.get(3) == 3 # now 1 and 3 both have count 2c.put(4, 4) # tie on count: evict 1, the older useassert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4 random.seed(5)for _ in range(300): cap = random.randint(0, 4) fast, slow = LFUCache(cap), SlowLFU(cap) for _ in range(80): k = random.randint(0, 6) if random.random() < 0.5: assert fast.get(k) == slow.get(k) else: fast.put(k, k * 10); slow.put(k, k * 10)print("LFU matches the reference on 300 random scripts")
Output
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 it in order4 steps

Put the steps of LFU put(key, value) for a NEW key, with the cache full, in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
import heapqimport itertoolsimport random class MinStack: def __init__(self): self.items = [] # (value, min of the stack up to here) def push(self, x): current_min = min(x, self.items[-1][1]) if self.items else x self.items.append((x, current_min)) def pop(self): self.items.pop() def top(self): return self.items[-1][0] def get_min(self): return self.items[-1][1] # popping restores the old minimum for free class MaxStack: """push, pop, top, peek_max, pop_max. Heap + stack with lazy deletion.""" def __init__(self): self.stack = [] # (value, id) self.heap = [] # (-value, -id): max value, newest first self.removed = set() # ids deleted from the other structure self.ids = itertools.count() def push(self, x): i = next(self.ids) self.stack.append((x, i)) heapq.heappush(self.heap, (-x, -i)) # negate: heapq is a min-heap def _clean_stack(self): while self.stack[-1][1] in self.removed: self.removed.discard(self.stack.pop()[1]) def _clean_heap(self): while -self.heap[0][1] in self.removed: self.removed.discard(-heapq.heappop(self.heap)[1]) def top(self): self._clean_stack() return self.stack[-1][0] def pop(self): self._clean_stack() x, i = self.stack.pop() self.removed.add(i) # the heap copy is now stale return x def peek_max(self): self._clean_heap() return -self.heap[0][0] def pop_max(self): self._clean_heap() neg_x, neg_i = heapq.heappop(self.heap) self.removed.add(-neg_i) # the stack copy is now stale return -neg_x s = MinStack()for x in [5, 3, 7, 3, 1]: s.push(x)assert s.get_min() == 1s.pop(); assert s.get_min() == 3s.pop(); assert s.get_min() == 3 # duplicate 3: each entry stores its own mins.pop(); s.pop(); assert s.get_min() == 5 and s.top() == 5 ms = MaxStack()for x in [5, 1, 5]: ms.push(x)assert ms.pop_max() == 5 and ms.top() == 1 # the NEWER 5 went firstassert ms.peek_max() == 5 and ms.pop() == 1 and ms.top() == 5 random.seed(4)ms, model = MaxStack(), []for _ in range(3000): op = random.random() if op < 0.4 or not model: x = random.randint(0, 9); ms.push(x); model.append(x) elif op < 0.6: assert ms.pop() == model.pop() elif op < 0.8: m = max(model); j = len(model) - 1 - model[::-1].index(m) assert ms.pop_max() == model.pop(j) else: assert ms.top() == model[-1] and ms.peek_max() == max(model)print("MinStack and MaxStack match a plain list model") # Python 3.14+ only: max-heap functions, no negation neededh = []for x in [3, 9, 4]: heapq.heappush_max(h, x)print(heapq.heappop_max(h), heapq.heappop_max(h))
Output
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).

RandomizedSet: remove(20) by swapping with the last element
10
0
20
1
30
2
40
3
pos = {10: 0, 20: 1, 30: 2, 40: 3}

The array holds the values. The map knows where each one lives.

1/4

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.

Python
import random class RandomizedSet: def __init__(self): self.vals = [] # the values, for O(1) random choice self.pos = {} # value -> its index in vals def insert(self, x): if x in self.pos: return False self.pos[x] = len(self.vals) self.vals.append(x) return True def remove(self, x): if x not in self.pos: return False i, last = self.pos[x], self.vals[-1] self.vals[i] = last # move the last value into the hole self.pos[last] = i self.vals.pop() # O(1): only ever pop from the end del self.pos[x] # AFTER updating last, in case x is last return True def get_random(self): return random.choice(self.vals) rs = RandomizedSet()assert rs.insert(10) and rs.insert(20) and rs.insert(30) and rs.insert(40)assert not rs.insert(20)assert rs.remove(20) and not rs.remove(20)assert rs.vals == [10, 40, 30] and rs.pos == {10: 0, 40: 1, 30: 2}assert rs.remove(30) # removing the last element itselfassert 30 not in rs.pos random.seed(2)model, rs = set(), RandomizedSet()for _ in range(2000): x = random.randint(0, 15) if random.random() < 0.5: assert rs.insert(x) == (x not in model); model.add(x) else: assert rs.remove(x) == (x in model); model.discard(x) assert set(rs.vals) == model and all(rs.vals[i] == v for v, i in rs.pos.items())print("RandomizedSet matches a set over 2000 random operations")
Output
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.

Python
from collections import deque class PeekingIterator: """Wraps any iterator and adds peek(), by reading one item ahead.""" _END = object() # sentinel: None could be a real value def __init__(self, iterator): self._it = iterator self._next = next(self._it, self._END) def peek(self): return self._next def has_next(self): return self._next is not self._END def next(self): value = self._next self._next = next(self._it, self._END) return value class NestedIterator: """Flatten Nested List Iterator: lazy, a stack of iterators.""" def __init__(self, nested): self.stack = [iter(nested)] def has_next(self): # Do the work here: dig until the next integer is on top, or we run out. while self.stack: try: item = next(self.stack[-1]) except StopIteration: self.stack.pop() continue if isinstance(item, list): self.stack.append(iter(item)) else: self.stack.append(iter([item])) # park it so next() can take it return True return False def next(self): self.has_next() # callers may skip has_next() return next(self.stack.pop()) def flatten(nested): """The generator version: the language keeps the stack for you.""" for item in nested: if isinstance(item, list): yield from flatten(item) else: yield item def zigzag(*lists): """Zigzag Iterator for any number of lists: a queue of (list, next index).""" queue = deque((xs, 0) for xs in lists if xs) while queue: xs, i = queue.popleft() yield xs[i] if i + 1 < len(xs): queue.append((xs, i + 1)) # still has items: back of the line p = PeekingIterator(iter([1, None, 3]))assert p.peek() == 1 and p.next() == 1assert p.has_next() and p.peek() is None and p.next() is None # None is data, not "empty"assert p.next() == 3 and not p.has_next() data = [[1, [2, []]], [], 3, [[[4]]], []]it, out = NestedIterator(data), []while it.has_next(): out.append(it.next())assert out == [1, 2, 3, 4] == list(flatten(data))assert NestedIterator([[], [[]]]).has_next() is False # empty lists must not count it = NestedIterator([[7], 8])assert it.next() == 7 and it.next() == 8 # works without has_next() assert list(zigzag([1, 2], [3, 4, 5, 6], [], [7])) == [1, 3, 7, 2, 4, 5, 6]print(out, list(zigzag([1, 2], [3, 4, 5, 6])))
Output
Press Run (⌘ Enter) to see what happens.

The same ideas in JavaScript, where the protocol is an object with next() returning { value, done }:

JavaScript
// The protocol: next() returns { value, done }.class PeekingIterator { constructor(iterator) { this.it = iterator; this.buf = this.it.next(); // read one ahead } peek() { return this.buf.value; } hasNext() { return !this.buf.done; } next() { const out = this.buf.value; this.buf = this.it.next(); return out; }} // A generator function builds an iterator for you.function* flatten(nested) { for (const item of nested) { if (Array.isArray(item)) yield* flatten(item); else yield item; }} const p = new PeekingIterator(flatten([1, [2, [3]], [], 4]));console.log("peek:", p.peek(), "next:", p.next(), "peek:", p.peek());const rest = [];while (p.hasNext()) rest.push(p.next());console.log("rest:", rest.join(" ")); const raw = [10, 20][Symbol.iterator]();console.log(raw.next(), raw.next(), raw.next());
Output
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.

Python
from bisect import bisect_rightfrom collections import defaultdict, deque class TimeMap: """Time Based Key-Value Store. Timestamps arrive in increasing order.""" def __init__(self): self.times = defaultdict(list) # key -> [t1, t2, ...] sorted self.values = defaultdict(list) # key -> values, parallel to times def set(self, key, value, timestamp): self.times[key].append(timestamp) # append keeps it sorted for free self.values[key].append(value) def get(self, key, timestamp): i = bisect_right(self.times[key], timestamp) # first time AFTER timestamp return self.values[key][i - 1] if i else "" class HitCounter: """Hits in the last 300 seconds. Timestamps never go backwards.""" WINDOW = 300 def __init__(self): self.hits = deque() # (timestamp, count), oldest left def hit(self, t): if self.hits and self.hits[-1][0] == t: self.hits[-1] = (t, self.hits[-1][1] + 1) # compress bursts else: self.hits.append((t, 1)) def get_hits(self, t): while self.hits and self.hits[0][0] <= t - self.WINDOW: self.hits.popleft() # each hit leaves once: amortised O(1) return sum(c for _, c in self.hits) class SnapshotArray: """set, snap, get(index, snap_id). Store changes, not copies.""" def __init__(self, length): self.history = [[(-1, 0)] for _ in range(length)] # per index: (snap_id, value) self.snap_id = 0 def set(self, index, val): h = self.history[index] if h[-1][0] == self.snap_id: h[-1] = (self.snap_id, val) # overwrite within the same snapshot else: h.append((self.snap_id, val)) def snap(self): self.snap_id += 1 return self.snap_id - 1 def get(self, index, snap_id): h = self.history[index] i = bisect_right(h, (snap_id, float("inf"))) # last change at or before snap_id return h[i - 1][1] tm = TimeMap()tm.set("price", "100", 1)tm.set("price", "120", 4)assert tm.get("price", 0) == ""assert tm.get("price", 1) == "100"assert tm.get("price", 3) == "100"assert tm.get("price", 4) == "120" and tm.get("price", 99) == "120"assert tm.get("missing", 5) == "" hc = HitCounter()for t in [1, 2, 3, 3]: hc.hit(t)assert hc.get_hits(4) == 4hc.hit(300)assert hc.get_hits(300) == 5assert hc.get_hits(301) == 4 # the hit at t=1 has left the windowassert hc.get_hits(599) == 1 and hc.get_hits(600) == 0 sa = SnapshotArray(3)sa.set(0, 5)assert sa.snap() == 0sa.set(0, 6); sa.set(0, 7)assert sa.snap() == 1assert sa.snap() == 2assert sa.get(0, 0) == 5 and sa.get(0, 1) == 7 and sa.get(0, 2) == 7assert sa.get(1, 2) == 0print(tm.get("price", 3), sa.get(0, 0), sa.history[0])
Output
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 the pairs0/5 matched

Match each design problem to the structures it combines.

Choose an item, then its match on the other side.

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_end followed 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.
locked_lru.py
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)
Quick check
Why does a read-write lock (many readers, one writer) not speed up a shared LRU cache?
Need a nudge? A hint rules out a wrong answer.

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.

Key terms
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__ raises StopIteration at the end. JavaScript: next() returns { value, done }.
generator
A function with yield that returns an iterator and pauses between items, keeping its local state.
LFU
Least frequently used eviction. Ties are broken by recency, and min_freq tracks 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.