LRU Cache
The least recently used cache from first principles: why a hash map alone and a list alone both fail, the hash map plus doubly linked list design with sentinels, get as move-to-front and put as insert-and-evict, traced on capacity 3, implemented and run in JavaScript, the Map insertion-order shortcut, Python and Java equivalents, thread safety, common bugs, and a computed LRU versus LFU versus FIFO comparison.
Picture a small desk that holds only three books. Every time you open a book you slide it to the left edge of the desk, so the books drift to the right in the order you last touched them. When you bring a fourth book, the one on the far right, the book you have ignored the longest, goes back to the shelf. Finding a book is the hard part if the desk is a pile, so you also keep an index card that says exactly where each title sits. The index card is the hash map, the left-to-right row is the doubly linked list, and the whole design is those two pieces kept in agreement after every single operation.
Builds on
- Linked lists — the recency order is a doubly linked list, and you must be comfortable rewiring next and prev pointers without dropping a node.
- Sets and maps — the O(1) lookup comes from a hash map, and you should know what average O(1) promises.
- Big-O notation — we derive the cost of get and put by counting map operations and pointer writes.
- Caching — that lesson covers why caches exist and how eviction policies compare at system scale; this one builds the data structure underneath.
The problem: fast lookups, bounded memory
A cache keeps copies of data you recently needed so that asking again is fast. Memory is finite, so the cache has a capacity: a maximum number of entries. When it is full and a new entry arrives, something must be removed. That removal is an eviction, and the rule that picks the victim is the eviction policy. The most common rule is LRU (least recently used): discard the entry whose last access is the oldest. The bet behind it is that keys used recently are likely to be used again soon, and keys that have sat idle for a long time are not.
The interview version of the problem fixes two methods. get(key) returns the value if the key is present, otherwise -1, and counts as a use of the key. put(key, value) inserts or updates the key, counts as a use, and if the cache now exceeds its capacity it evicts the least recently used key. Both methods must run in O(1) time. That last sentence is what makes the question hard, because the obvious structures each break it.
Try a hash map by itself. It finds any key in average O(1) time, which handles lookups. But a hash map keeps no notion of 'which key was used longest ago'. To find the eviction victim you would have to look at every entry's timestamp, which is O(n) per eviction. Storing a last-used timestamp in each entry fixes nothing, because finding the smallest timestamp is still a scan of all n entries.
Now try a list by itself, ordered by recency with the most recent at the front. The victim is always at the back, so eviction is cheap. But finding a key inside the list means walking from the front comparing as you go, O(n) in the worst case. You also cannot cheat with an array: moving an element to the front shifts everything before it, O(n) again. A list gets the order right and the lookup wrong; a hash map gets the lookup right and the order wrong.
| Structure alone | Find a key | Know the oldest key | Move a key to 'most recent' | Verdict |
|---|---|---|---|---|
| hash map only | O(1) average | O(n): scan every entry | Nothing to move; no order exists | Fails eviction |
| array ordered by recency | O(n) walk | O(1): last slot | O(n): shift the elements | Fails lookup and move |
| Singly linked list | O(n) walk | O(n) to reach the tail without a tail pointer | O(n): need the predecessor | Fails lookup and move |
| hash map + doubly linked list | O(1) average | O(1): node before the tail sentinel | O(1): unlink and relink | Meets the requirement |
Check yourself
Why can a hash map alone not meet the O(1) requirement for eviction?
The design: hash map plus doubly linked list
The design has two parts that share the same nodes. The hash map maps each key to its list node, not to the value. The doubly linked list holds one node per cached entry, ordered by recency: the node right after the head sentinel is the most recently used, and the node right before the tail sentinel is the least recently used. Each node stores the key, the value, a prev pointer and a next pointer.
Why must the node store its own key? Because of eviction. When the cache is full you reach the victim through the tail sentinel's prev, and you then need to delete that victim's entry from the hash map. The map is keyed by the key, so the node has to remember it. Forgetting this, and storing only the value in the node, leaves you unable to clean up the map.
Why doubly linked? Look at what a hit does. The map hands you the node for a key. To move it to the front you must first unlink it from its current place, which means setting the previous node's next to skip over it. In a singly linked list the node does not know its predecessor, so you would walk from the front to find it, an O(n) step that destroys the whole design. With a prev pointer in every node, the predecessor is one hop away and unlinking touches only two neighbors.
Why sentinels? Without them, the first and last real nodes are special: the first has no previous node, the last has no next node, and a one-element list is both at once. Every unlink and insert then needs branches such as 'if node is head, update the head variable'. Two permanent dummy nodes, a head sentinel and a tail sentinel that never hold data, remove all of that. Every real node always has a real neighbor on each side, so unlink is always the same two writes and insert-at-front is always the same four.
Invariant one
the set of keys in the hash map equals the set of keys in the list, always, between operations. If it ever differs, you have a ghost entry or an unreachable node.
Invariant two
reading the list from head to tail gives keys from most to least recently used.
Invariant three
the number of real nodes never exceeds the capacity after an operation finishes.
Invariant four
every pointer pair agrees, meaning node.next.prev is node and node.prev.next is node for all nodes including sentinels.
Check yourself
A cache hit gives you a node from the hash map. Why is a prev pointer needed to move it to the front in O(1)?
get and put, step by step
Two tiny helpers carry all the pointer work. unlink(node) removes a node from wherever it is: node.prev.next = node.next and node.next.prev = node.prev. That is two writes, and thanks to the sentinels it needs no branches. addFront(node) inserts a node right after the head sentinel: set node.next to the current first node, set node.prev to the head sentinel, point the old first node's prev back at node, and finally point the head sentinel's next at node. That is four writes. Every operation is a combination of these two helpers plus a hash map call.
01get(key): look up
Ask the hash map for the node. If there is none, return -1 and change nothing: a miss does not alter recency.
02get(key): promote
Unlink the node and add it to the front. Six pointer writes in total. Return its value.
03put(key, value): existing key
Ask the map for the node. If it exists, overwrite node.value, then unlink and add to the front. An update is a use, so recency must refresh too.
04put(key, value): new key at capacity
If the map size equals the capacity, take the victim as tail.prev, unlink it, and delete victim.key from the hash map. Both structures lose the entry.
05put(key, value): insert
Create a node, store it in the map under key, and add it to the front.
The order of the eviction and insertion steps matters. Evict before inserting so the cache never exceeds its capacity, even briefly, and so a capacity of 1 behaves: the old entry leaves, then the new one arrives. Also check for an existing key first. If you evicted before checking, a plain update of a key already in a full cache would needlessly throw away an innocent entry.
| Operation | Map calls | Pointer writes | Notes |
|---|---|---|---|
| get hit | 1 lookup | 6 (unlink 2 + addFront 4) | Returns the value; node now first |
| get miss | 1 lookup | 0 | Returns -1; nothing changes |
| put, key exists | 1 lookup | 6 | Overwrite value, then promote |
| put, new key, room left | 1 lookup + 1 set | 4 | Just addFront |
| put, new key, full | 1 lookup + 1 delete + 1 set | 6 (evict 2 + addFront 4) | Evict tail.prev first, then insert |
Check yourself
A full cache of capacity 3 receives put(9, 'x') where key 9 is new. Which sequence is correct?
Complexity derived, and the memory bill
Complexity is a count, so count. A hit performs one map lookup, then unlink (2 pointer writes) then addFront (4 pointer writes). The number 6 does not depend on how many entries are cached, which is the definition of constant time. A put of a new key at capacity performs one lookup, reads tail.prev, does one unlink (2 writes), one map delete, one map set, and one addFront (4 writes). Again fixed: 6 writes and 3 map calls. There is no loop anywhere in either method, so no input can make them longer.
A careful answer adds one caveat. The hash map is average O(1), not guaranteed O(1): if many keys collide into one bucket, a lookup can degrade toward O(n) in the worst case (see sets and maps). So the honest statement is that get and put are O(1) on average, with the list work always exactly constant. In an interview, say 'O(1) average, because of the hash map' and move on; it shows you know the difference without derailing the answer.
Space is O(capacity), because both structures hold at most capacity entries. We can be more precise with a model. Assume a 64-bit machine, 8-byte keys, 8-byte values and 8-byte pointers, and ignore language object headers and allocator padding (a real JavaScript engine adds its own, so this is a model, not a measurement). Each list node holds key, value, prev and next: 4 x 8 = 32 bytes. Each map entry holds a key and a pointer to the node: 2 x 8 = 16 bytes. So one cached entry costs about 48 bytes in this model.
Compare with a plain map: 16 bytes per entry in the same model. LRU bookkeeping triples the footprint, and 16 of the extra 32 bytes are the two list pointers. That is the price of O(1) recency tracking. The cost is why very large production caches often use cheaper approximations, covered in the extensions section.
Check yourself
Which statement about the complexity of get is the most accurate?
Implementation in JavaScript
Here is the whole design in one class. It follows the invariants from the design section: every node knows its key, the sentinels never hold data, evict happens before insert, and put on an existing key both updates and promotes. We also include an order() method that reads the list from head to tail, purely so we can print and check the invariants in a demo. The code was run in Node and the output shown is what it printed.
class Node { constructor(key, value) { this.key = key; this.value = value; this.prev = null; this.next = null; }} class LRUCache { constructor(capacity) { this.capacity = capacity; this.map = new Map(); // key -> Node this.head = new Node(null, null); // sentinel: most recent side this.tail = new Node(null, null); // sentinel: least recent side this.head.next = this.tail; this.tail.prev = this.head; } _unlink(node) { node.prev.next = node.next; node.next.prev = node.prev; } _addFront(node) { node.next = this.head.next; node.prev = this.head; this.head.next.prev = node; this.head.next = node; } get(key) { const node = this.map.get(key); if (node === undefined) return -1; this._unlink(node); this._addFront(node); return node.value; } put(key, value) { if (this.capacity <= 0) return; const existing = this.map.get(key); if (existing !== undefined) { existing.value = value; this._unlink(existing); this._addFront(existing); return; } if (this.map.size === this.capacity) { const lru = this.tail.prev; this._unlink(lru); this.map.delete(lru.key); } const node = new Node(key, value); this.map.set(key, node); this._addFront(node); } order() { const out = []; for (let n = this.head.next; n !== this.tail; n = n.next) out.push(n.key); return out; }} const c = new LRUCache(3);c.put(1, 'A'); c.put(2, 'B'); c.put(3, 'C');console.log(c.order().join(',')); // 3,2,1console.log(c.get(1), c.order().join(',')); // A 1,3,2c.put(4, 'D');console.log(c.order().join(','), c.get(2)); // 4,1,3 -1c.put(3, 'C2');console.log(c.order().join(','), c.get(3)); // 3,4,1 C2console.log(c.get(4), c.order().join(','), c.map.size); // D 4,3,1 3 const zero = new LRUCache(0); zero.put(1, 'x');console.log(zero.get(1)); // -1const one = new LRUCache(1); one.put(1, 'a'); one.put(2, 'b');console.log(one.get(1), one.get(2)); // -1 bRead the output against the prose. After three puts the order is 3,2,1 because each new key goes to the front. get(1) returns A and moves key 1 to the front, giving 1,3,2. put(4) finds the cache full, evicts key 2 (the node before the tail), and inserts 4, giving 4,1,3; the next get(2) returns -1, proving that key 2 left the map as well as the list. put(3, 'C2') updates an existing key and promotes it. The last line shows the map size stays at 3. The two final checks cover capacity 0 (nothing is ever stored) and capacity 1 (each put replaces the previous entry).
The iterative nature matters too. There is no recursion anywhere, so no stack depth concern for large caches, and every method does a fixed amount of work. Compare the linked list techniques in linked list: the pointer-writing order there (set the new node's pointers first, publish last) is the same discipline used in _addFront.
Check yourself
In put, why does the code check the map for an existing key before evicting?
The JavaScript Map shortcut and how interviewers see it
A JavaScript Map remembers the order in which keys were first inserted, and iterates in that order. Mozilla's JavaScript reference states that iteration happens in insertion order, corresponding to the order in which each pair was first inserted by set(), meaning there was not already a key with the same value in the map at the time. Two consequences follow. First, calling set on a key that already exists updates the value but does not change its position. Second, if you delete a key and then set it again, it is a brand-new insertion and lands at the end. Delete plus set is therefore a way to say 'move this key to the most recent end'.
That gives a one-structure LRU. The front of the iteration order (map.keys().next().value) is the oldest-touched key and the end is the newest. On get, delete and re-set. On put, if the key exists delete it first; otherwise, if the map is full, delete the first key; then set. It is short and correct:
class MapLRU { constructor(capacity) { this.capacity = capacity; this.map = new Map(); } get(key) { if (!this.map.has(key)) return -1; const v = this.map.get(key); this.map.delete(key); // remove... this.map.set(key, v); // ...and re-insert at the newest end return v; } put(key, value) { if (this.capacity <= 0) return; if (this.map.has(key)) this.map.delete(key); else if (this.map.size === this.capacity) { this.map.delete(this.map.keys().next().value); // oldest key } this.map.set(key, value); }} const m = new MapLRU(3);m.put(1, 'A'); m.put(2, 'B'); m.put(3, 'C'); m.get(1); m.put(4, 'D');console.log([...m.map.keys()].join(','), m.get(2)); // 3,1,4 -1 const mm = new Map([['a', 1], ['b', 2], ['c', 3]]);mm.set('a', 9);console.log([...mm.keys()].join('')); // abc (set on an existing key keeps its place)mm.delete('a'); mm.set('a', 9);console.log([...mm.keys()].join('')); // bca (delete then set moves it to the end)The output confirms the semantics: after the same operations as the main trace, the oldest-to-newest order is 3,1,4 and key 2 is gone. What does the language promise about speed? The specification only requires Map operations to be sublinear in the number of entries, and does not mandate a single data structure. In practice engines use hash tables, so delete, set and get are expected O(1), and reading the first key with keys().next() should be cheap too, but state it as 'in practice, on common engines' rather than as a guarantee.
| Aspect | Map + doubly linked list | Map insertion-order shortcut |
|---|---|---|
| Code size | About 60 lines with helpers | About 15 lines |
| Shows pointer mastery | Yes: you implement unlink and addFront | No: the engine hides the ordering structure |
| Moves per hit | 6 pointer writes you can count | Delete plus set; cost is the engine's concern |
| Portable across languages | Yes: any language with a hash map and a list | Only where the map preserves insertion order |
| Good for production JavaScript | Fine, but more code to maintain | Often the pragmatic choice |
Check yourself
After map.set('a', 1), map.set('b', 2), then map.set('a', 3), what is the iteration order of the keys?
What Python and Java already give you
Other languages ship the building blocks. In Python, collections.OrderedDict remembers insertion order and adds move_to_end(key, last=True), which, per the Python documentation, moves an existing key to either end of the dictionary (the right end by default, the beginning if last is false) and raises KeyError if the key does not exist. It also has popitem(last=True), which pops last-in-first-out when last is true and first-in-first-out when false. The documentation notes an OrderedDict is useful for implementing variants of functools.lru_cache, and its recipes use exactly this pair: move_to_end on a hit and popitem(last=False) to evict the oldest. Here is a class written that way, run with Python 3 and showing its output, with a lock because get mutates order:
from collections import OrderedDictimport threading class LRUCache: def __init__(self, capacity): self.capacity = capacity self.data = OrderedDict() self.lock = threading.Lock() def get(self, key): with self.lock: if key not in self.data: return -1 self.data.move_to_end(key) # mark most recent return self.data[key] def put(self, key, value): with self.lock: if self.capacity <= 0: return if key in self.data: self.data.move_to_end(key) self.data[key] = value if len(self.data) > self.capacity: self.data.popitem(last=False) # evict oldest c = LRUCache(3)for k, v in [(1, 'A'), (2, 'B'), (3, 'C')]: c.put(k, v)print(c.get(1)) # Ac.put(4, 'D')print(list(c.data), c.get(2)) # [3, 1, 4] -1Python's functools.lru_cache is a different tool: a decorator that memoizes a function's results, not a general key-value cache you call get and put on. Per the documentation, @lru_cache(maxsize=128, typed=False) keeps the maxsize most recent calls (128 by default; None removes the limit so it can grow without bound), arguments must be hashable because results live in a dictionary, cache_info() returns hits, misses, maxsize and currsize, and cache_clear() empties it. The documentation also states the cache is thread-safe so its data structure stays coherent, but the wrapped function may be called more than once for the same arguments if two threads race, because locks are not held during the call. Run result for a size-2 cache over sq(1), sq(2), sq(1), sq(3), sq(2): CacheInfo(hits=1, misses=4, maxsize=2, currsize=2), since sq(3) evicts key 2 and the final sq(2) misses.
In Java, LinkedHashMap is a hash table whose entries are also threaded onto a doubly linked list, which is exactly our design built in. The three-argument constructor LinkedHashMap(initialCapacity, loadFactor, accessOrder) with accessOrder set to true makes the iteration order the order of last access, from least recently to most recently accessed. In that mode, calls such as put, get, getOrDefault, compute and merge count as accesses and move the entry to the end. Subclass it and override removeEldestEntry(Map.Entry eldest), which put and putAll call after inserting; returning true removes the eldest entry. The Java documentation shows this as a simple LRU cache that returns size() > MAX_ENTRIES.
| Language | Tool | Recency refresh | Eviction | Thread safety per docs |
|---|---|---|---|---|
| JavaScript | Map | delete then set | delete keys().next().value | Single-threaded event loop; no built-in lock needed for synchronous methods |
| Python | OrderedDict | move_to_end(key) | popitem(last=False) | Add your own lock |
| Python | functools.LRU_cache | Automatic per call | Automatic at maxsize | cache is thread-safe; the function may run twice |
| Java | LinkedHashMap accessOrder true | Automatic on get and put | removeEldestEntry returns true | Not synchronized; wrap externally. In access order, get is a structural change |
Check yourself
In Java's LinkedHashMap with accessOrder set to true, which entry is the 'eldest' that removeEldestEntry is offered?
Thread safety: why even get needs a lock
Most data structures can be read by many threads at once as long as nobody writes. An LRU cache breaks that rule, because get is a write. A hit unlinks a node and relinks it at the front, touching four or more pointers. Two threads running get at the same time can interleave those writes and leave a node pointing at a neighbor that has already been unlinked, which corrupts the list for every later operation. The hash map and the list must also change together; a thread that sees the node removed from the list but not yet deleted from the map observes a state that violates the invariants.
The simplest correct fix is one mutex (a lock) around the entire public operation. Acquire it at the start of get and put, release at the end, and the whole body, map call plus pointer writes plus eviction, behaves as one indivisible step. The scope matters: locking the map and the list separately is not enough, because another thread can slip in between the two updates. The Python example above does exactly this with with self.lock.
A single lock serializes all operations, so under heavy concurrency it becomes a bottleneck. The usual next step is sharding (also called striping): hash the key to pick one of N independent smaller LRU caches, each with its own lock. Threads touching different shards no longer contend. The cost is that eviction is now only locally least recently used: the globally oldest entry might sit in a shard that is not full yet, so the strict LRU guarantee is traded for throughput. Name that trade-off explicitly in an interview.
| Approach | Contention | Correctness | Trade-off |
|---|---|---|---|
| One lock around each operation | All threads serialize | Exact LRU | Simple; the lock is the bottleneck under heavy load |
| Sharded caches, one lock each | Only same-shard threads wait | LRU within each shard only | Higher throughput; approximate global order |
| Read lock for get | Not valid | Corrupts the list | get mutates order, so it needs the exclusive lock |
| Record accesses in a buffer, apply later | Low on reads | Order is slightly stale | Complex; used by high-performance libraries |
What about JavaScript? A single JavaScript thread runs each synchronous method to completion before anything else runs, so get and put in our class are already atomic with respect to other code on the same event loop. You only need to think about it if you introduce asynchronous steps inside an operation (such as awaiting a fetch between the check and the insert), or share state across worker threads through message passing, which copies data rather than sharing the object.
Check yourself
Why is a shared read lock around get unsafe in an LRU cache?
Common bugs and edge cases
LRU code is short enough that interviewers can read all of it, and a small set of mistakes accounts for nearly every failure. Each one violates one of the four invariants from the design section, so the quickest way to debug is to ask which invariant just broke. The table lists the bug, the symptom you would see, and the defense.
| Bug | Symptom | Invariant broken | Defense |
|---|---|---|---|
| Evict from the list but not the map | get on an evicted key returns a stale value; map size grows past capacity | Map and list hold the same keys | Store the key in the node; delete node.key from the map when evicting |
| get does not move the node | Recently read keys get evicted early; hit rate collapses | List ordered by recency | Every hit unlinks and re-adds at the front |
| put on existing key updates the value only | Updated key stays near the tail and is evicted soon after | List ordered by recency | Update the value, then promote |
| put on existing key inserts a second node | Duplicate nodes; the map points at one, the other is orphaned | Map and list hold the same keys | Check the map first; update in place |
| Evicting before checking for an existing key | A needless eviction on a plain update | capacity respected, but data lost | Check existence, then evict only for new keys |
| capacity 0 not handled | Evicting from an empty list reads the head sentinel as a victim | Number of nodes never exceeds capacity | Return early in put when capacity <= 0 |
| capacity 1 evicts the new entry | Stores nothing, or crashes | Order of evict then insert | Evict first, then insert; the one-node list works with sentinels |
| Pointers written in the wrong order in addFront | Lost nodes, cycles, or a broken tail | pointer pairs agree | Set the new node's pointers first, then fix the neighbors |
Beyond these, think about what get returns for a stored value that happens to be -1, 0 or null. The problem statement uses -1 as the miss signal, so storing -1 as a legitimate value makes the two cases indistinguishable. In real code, return undefined or a result object instead; in the interview version, ask whether values can be negative. Also notice the check node === undefined rather than !node in our code, which keeps a falsy but valid node from being mistaken for a miss.
Check yourself
A cache of capacity 2 runs put(1), put(2), put(1, 'new'), put(3). If put on an existing key forgets to promote, which key is wrongly evicted?
LRU versus LFU versus FIFO, with a computed comparison
LRU is one policy among several. FIFO evicts the entry that arrived earliest, ignoring whether it is still being used; it is trivial to implement (a queue) but blind to access patterns. LFU evicts the entry used the fewest times, tracking a counter per key; it favors entries that were hot over a long period. LRU favors entries touched most recently. For the system-level view of choosing among policies, see caching; here we simply measure them.
We simulated all three on capacity 3 with three access sequences, one letter per key access. Assumptions: LFU counts accesses since the key last entered the cache (a counter resets when its key is evicted) and breaks ties by evicting the least recently used among the least frequent. A hit leaves a FIFO queue unchanged. The results were computed by a short node script, and the hit counts below were checked by tracing by hand.
| Sequence (capacity 3) | Length | FIFO hits | LRU hits | LFU hits |
|---|---|---|---|---|
| A B C A B D A B E A B C A B D (steady working set A, B) | 15 | 4 (26.7%) | 8 (53.3%) | 8 (53.3%) |
| A B A B A B C D E F A B A B (hot pair, then a one-time scan) | 14 | 6 (42.9%) | 6 (42.9%) | 8 (57.1%) |
| A A A A B B B B C D C D C D C D C D C D (working set shifts) | 20 | 16 (80.0%) | 16 (80.0%) | 6 (30.0%) |
Walk through the first row for LRU. A, B, C are misses (3 misses, cache full). The next A and B hit (2 hits). D misses and evicts C, the least recently used, leaving A, B, D. Then A, B hit (2 more hits, total 4). E misses and evicts D. The next A and B hit (total 6). C misses and evicts E. A and B hit again (total 8). The last D misses. Final: 8 hits of 15. FIFO does worse because it keeps evicting by arrival order: after D arrives it evicts A, the oldest arrival, even though A is hot, so A and B keep getting thrown out and re-fetched.
The second row shows a scan: the hot pair A, B is used repeatedly, then C D E F each appear once, then the pair returns. LRU lets the one-time keys push A and B out (after C D E F, the cache is D E F), so the final A and B each miss, while LFU protects A and B because their counts are high and evicts the one-hit keys instead. The third row is the reverse: after A and B have been used four times each, the program moves on to C and D alternately. LFU keeps A and B forever because their counts are high and leaves one slot for C and D to fight over, so every access to them misses; LRU notices A and B have gone cold and adapts. LFU's fix is to age or decay counters.
| Policy | Strength | Weakness | Typical structure |
|---|---|---|---|
| LRU | Adapts to a changing working set; simple | A one-time scan flushes the hot keys; cyclic access over more keys than capacity misses every time | hash map + doubly linked list |
| LFU | Resists scans; keeps long-term hot keys | Clings to stale hot keys; needs counters and decay | hash map + frequency buckets |
| FIFO | Cheapest; no work on a hit | Evicts hot keys just because they arrived early | queue + hash set |
Check yourself
A program reads every row of a huge table exactly once while a small set of hot keys is also used. What problem does this cause for plain LRU?
Extensions, approximations and the interview script
Interviewers love follow-ups once the BASE design stands. TTL (time to live): store an expiry time in each node. On get, check it first and treat an expired entry as a miss, removing it. This is lazy expiry. You may also run a background sweep (active expiry) so entries that are never read again do not occupy memory. Expiry stays O(1) per check; sweeping is bounded work per pass.
Size-weighted entries: when entries have different byte sizes, capacity becomes a total weight instead of a count. Track the running total; after inserting, evict from the tail repeatedly until the total fits. A single put can now cause several evictions, so it is amortized O(1) rather than strictly O(1): each entry is evicted at most once for each time it was inserted, so over m puts the total eviction work is at most m.
Approximate LRU: exact LRU costs two pointers per entry and a write on every hit, which is expensive for enormous caches and for memory pages. Systems therefore approximate it. The clock (second chance) algorithm keeps a reference bit per entry in a circular buffer; a hit sets the bit, and the eviction hand sweeps, clearing set bits and evicting the first entry whose bit is already clear. It needs no list reordering on a hit. Other systems sample a few random entries and evict the oldest of the sample. Both trade exactness for lower per-access cost, and real operating systems and caches are generally described as using approximations of LRU rather than exact lists. Recognize the idea; do not quote implementation details you have not checked.
Related problems unlock naturally from this one. Design hashmap rehearses the hash table half; min stack practices keeping two structures in sync; merge k sorted lists and priority queue cover other recency or ordering structures; and an LFU cache is the standard harder sibling. Finally, here is a timed script that fits an interview slot.
01Minute 0 to 2: clarify
Confirm get returns -1 on a miss, that put updates existing keys, what capacity 0 means, and whether values can be -1. State that both operations must be O(1).
02Minute 2 to 5: argue the design
A map alone cannot find the oldest key; a list alone cannot find a key. Combine a hash map to nodes with a doubly linked list. Say why doubly linked and why sentinels.
03Minute 5 to 8: state the invariants
Map and list hold the same keys; list ordered most to least recent; size never exceeds capacity. Draw a three-entry example.
04Minute 8 to 22: code
Write node, unlink, addFront, get, put. Evict before insert, and update-and-promote for an existing key.
05Minute 22 to 27: test aloud
Run capacity 2: put 1, put 2, get 1, put 3, get 2 expecting a miss. Then capacity 1 and an update in a full cache.
06Minute 27 to 35: follow-ups
Mention the Map shortcut, a lock around each whole operation, sharding trade-offs, TTL, and the LRU versus LFU scan trade-off.
Recap
Requirement: get and put in O(1), and when full, drop the entry that has gone unused the longest.
A hash map alone has no order, so it cannot find the least recently used key without scanning all n entries. A list alone keeps order but needs an O(n) walk to find a key. Together they cover each other's weakness.
The map stores key to node; the doubly linked list stores recency, head most recent, tail least recent. The two must always hold exactly the same set of keys.
Doubly linked because a node you hold must be unlinked in O(1), which needs its prev pointer. Sentinels at both ends remove every null check.
get: map lookup, then unlink and re-insert at the front (6 pointer writes). put on an existing key: update the value AND move to the front. put on a new key at capacity: unlink the node before the tail sentinel, delete its key from the map, insert the new node at the front.
In JavaScript a Map iterates in insertion order, so delete plus set refreshes recency and keys().next() is the oldest. It is a legitimate shortcut, but interviewers usually want the two-structure design explained first.
Python has OrderedDict.move_to_end and popitem(last=False); functools.LRU_cache memoizes a function; Java has LinkedHashMap with accessOrder true and removeEldestEntry. In all of them a read changes order, so a read needs the lock too.
LRU adapts to a shifting working set but is hurt by scans; LFU resists scans but clings to stale hot keys; FIFO ignores usage entirely. On the sequences in this lesson hit counts differ by 2x or more.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
data structure
A way of organizing data in memory (array, tree, map) that determines which operations are fast.
priority queue
A queue that always hands out the highest-priority item first, usually backed by a heap.
two pointers
Moving two indices through an array to meet a condition in one pass instead of nested loops.
linked list
A chain of nodes where each points to the next, giving cheap inserts and deletes but O(n) access.
throughput
How many requests the system completes per second - total work, not individual speed.
amortized
Averaged over a long run of operations, so rare expensive steps are spread across many cheap ones.
recursion
A function that calls itself with a smaller version of the same problem until it hits a base case.
algorithm
A precise, step-by-step procedure that solves a problem.
invariant
A property that stays true throughout an algorithm, used to prove it correct.
hash map
A key-value structure that finds the value for a key in average O(1) time by hashing the key to a bucket.
An index card catalogue.
hash set
A hash map that stores only keys, used to answer 'have I seen this?' in O(1).
pointer
A variable that stores a memory address, letting structures link to each other.
array
A contiguous block of memory holding items in order, readable by index in O(1).
stack
A last-in-first-out structure: you push on top and pop from the top.
queue
A first-in-first-out structure: items leave in the order they arrived.
BASEBasically Available, Soft state, Eventually consistent
The looser set of guarantees NoSQL stores trade for scale: the system stays available, state is approximate, and replicas catch up over time.
node
One element in a linked structure, holding a value and pointers to its neighbors.
byte
Eight bits, the standard unit for one character or small number.
LRUleast recently used
An eviction rule that discards the entry whose last access is the oldest.
The book on your desk you have not opened for the longest time.
LFUleast frequently used
An eviction rule that discards the entry with the fewest accesses so far.
The book you have opened the fewest times in total.
bit
A single 0 or 1 - the smallest unit of data.
FIFOfirst in, first out
An eviction rule that discards the entry that was inserted earliest, ignoring how often or how recently it was used.
A queue at a shop: whoever arrived first leaves first.
TTLtime to live
A per-entry lifetime after which the entry counts as expired and is treated as a miss.
The use-by date printed on milk.
cache
A small, fast store that keeps copies of recently needed data so repeated requests skip the slow source.
capacity
The maximum number of entries the cache may hold. Inserting beyond it forces an eviction.
eviction
Removing an entry from a full cache to make room for a new one.
hit
A lookup that finds the key in the cache.
miss
A lookup that does not find the key; the caller must fetch it from the slow source.
hit rate
Hits divided by total lookups, usually quoted as a percentage. It is the number a cache exists to raise.
recency
How long ago an entry was last accessed. LRU keeps entries ordered by it.
working set
The set of keys a program actually keeps coming back to over a period of time.
doubly linked list
A chain of nodes where each node points to both its next and its previous node, so a node you hold can be unlinked with no search.
A train where every carriage is coupled to both neighbors.
sentinel
A permanent dummy node at each end of the list, so every real node always has a neighbor on both sides and no code path checks for null.
The two end stops on a bookshelf.
mutex
A lock that lets only one thread at a time run the code it protects.
A key to a single-person room.
scan
A burst of one-time accesses to many different keys, such as reading a whole table once. It pushes useful entries out of an LRU cache.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixThe map still points at a node that is no longer in the list, so a later get returns stale data and the map grows past capacity. Store the key in the node and delete it from both structures.
FixAn update is a use. Without promotion the key stays near the tail and is evicted soon after. Overwrite the value, then unlink and addFront.
FixA singly linked node cannot find its predecessor without an O(n) walk, so the list must be doubly linked. Guard capacity 0 with an early return, and evict before inserting so capacity 1 replaces the previous entry.
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
Use a hash map from key to node and a doubly linked list ordered most recent at the head, with sentinel head and tail nodes. get looks up the node and moves it to the front. put updates and promotes an existing key, or evicts tail.prev (removing its key from the map) when full and then inserts the new node at the front. The list work is a fixed number of pointer writes, so both are O(1) average, bounded by the hash map.
get, put O(1) average; space O(capacity)
Real worldThis is among the most common data structure design questions because it tests composition.
DeeperExpect to be asked why the list is doubly linked and why the node stores its key.