Constant-Time LRU Key-Value Cache
Hard · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build a bounded in-memory key-value store governed by the Least Recently Used (LRU) eviction rule, and expose a batch runner lru_cache_operations(capacity, operations, arguments) that replays a sequence of lookups and writes against a fresh cache of size capacity.
Cache Behavior
An LRUCache(capacity) instance holds up to capacity distinct integer keys mapped to integer values, tracking recency across every successful read and write:
get(key) -> int: Whenkeyis currently resident, markkeyas the most recently touched entry and return its associated value. Whenkeyis absent, return-1without modifying resident entries or their recency order.put(key, value) -> None:- When
keyis already resident, overwrite its stored value withvalueand promotekeyto the most recently touched position (no eviction occurs). - When
keyis not resident and the store already holdscapacitykeys, evict whichever resident key was touched least recently (considering bothgethits andputcalls), then insert(key, value)at the most recently touched position.
- When
class LRUCache:
def __init__(self, capacity: int):
pass
def get(self, key: int) -> int:
pass
def put(self, key: int, value: int) -> None:
pass
Batch Runner Signature
def lru_cache_operations(
capacity: int,
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
pass
Create one LRUCache(capacity) and execute (operations[i], arguments[i]) in order:
"get"with[key]: Append the integer returned bycache.get(key)."put"with[key, value]: Callcache.put(key, value)and appendNone.
Examples
Example 1
capacity = 2
operations = ["put", "put", "get", "put", "get", "get", "put", "get", "get"]
arguments = [[10, 50], [20, 60], [10], [30, 70], [20], [10], [40, 80], [30], [10]]
# Output: [None, None, 50, None, -1, 50, None, -1, 50]
Walk-through: After put(10, 50) and put(20, 60), key 10 is older than 20. Calling get(10) returns 50 and refreshes 10, making 20 the oldest entry. Inserting 30 evicts 20, so get(20) returns -1. Next get(10) returns 50 and refreshes 10 again, so put(40, 80) evicts 30 (get(30) -> -1) while 10 remains (get(10) -> 50).
Example 2
capacity = 2
operations = ["put", "put", "put", "put", "get", "get"]
arguments = [[5, 12], [8, 24], [5, 99], [9, 36], [5], [8]]
# Output: [None, None, None, None, 99, -1]
Walk-through: put(5, 12) and put(8, 24) fill both slots. put(5, 99) updates existing key 5 in place without evicting 8 and promotes 5 ahead of 8. The subsequent put(9, 36) therefore evicts 8, leaving 5 -> 99 and 8 -> -1.
Example 3
capacity = 1
operations = ["get", "put", "get", "put", "get", "get"]
arguments = [[0], [0, 0], [0], [7, 45], [0], [7]]
# Output: [-1, None, 0, None, -1, 45]
Walk-through: An initial lookup on an empty cache returns -1. Key 0 with value 0 is stored and retrieved (0), then displaced by put(7, 45) because capacity == 1.
Constraints
1 <= capacity <= 100,0000 <= key <= 1,000,0000 <= value <= 1,000,000,0000 <= len(operations) == len(arguments) <= 100,000- Both
getandputmust run inO(1)average time.
Step-by-step walkthrough
Understand the LRU cache rules
An LRU (Least Recently Used) cache stores at most
capacitykey-value pairs and remembers how recently each key was touched:get(key): Ifkeyis in the cache, mark it as most recently used and return its value; ifkeyis absent, return-1without changing the order of anything.put(key, value):- If
keyis already in the cache, update its value and mark it as most recently used (never evict anything on an overwrite). - If
keyis new and the cache is already atcapacity, evict the least recently used key first, then insert(key, value)as the most recently used entry.
- If
The judge calls
lru_cache_operations(capacity, operations, arguments)and expects one result per call (valueor-1for"get",Nonefor"put"). Withcapacityup to100,000, bothgetandputmust run inO(1)average time.Why a plain list or plain dictionary is not enough
Suppose we keep
[key, value]pairs in a Pythonlistordered from oldest to newest. Finding a key or removing it from the middle shifts up tocapacityelements —O(capacity)work per call, which balloons to10^10operations across100,000calls on a100,000-item cache.On the other hand, a plain Python dictionary (
dict) finds any key inO(1)average time, but by itself has no way to jump straight to an entry in the middle of a usage timeline and move it to the front without rebuilding order.To get
O(1)for both lookup and reordering, we pair two classic data structures together.Combine a hash map with a sentinel doubly linked list
Here is how each structure covers the other's blind spot:
- Doubly linked list (a chain of nodes where every node points to both
prevandnext): maintains the exact recency order from most recently used at the front to least recently used at the back. Given a direct reference to a node anywhere in the chain, splicing it out or inserting it at the front only rewires four neighbor pointers (O(1)time). - Hash map (
key_to_nodedictionary): maps eachkeydirectly to itsNodeobject inside the linked list inO(1)average time, so we never scan the list to find a node.
Two small structural choices eliminate almost every bug:
- Store
keyinsideNodeas well asvalue: When the cache is full, we find the victim at the back of the list (tail.prev). Havinglru_node.keyright on the node lets us rundel self.key_to_node[lru_node.key]inO(1)time. - Keep two permanent dummy sentinel nodes (
headandtail):headalways sits before the newest node, andtailalways sits after the oldest node. Becauseheadandtailare never deleted, every real node always has a non-Noneprevand a non-Nonenext— even when the cache is empty (head <-> tail) or holds a single item!
key_to_node = { 10: ──┐, 30: ──────────┐ } │ │ v v [head] <───> [Node(10, 50)] <───> [Node(30, 70)] <───> [tail] most recent least recent (head.next) (tail.prev)- Doubly linked list (a chain of nodes where every node points to both
Write bug-free `O(1)` pointer helpers
Every cache operation reduces to two tiny list primitives:
_remove(node)and_insert_after_head(node).Watch how
_insert_after_headsavesfirst_real = self.head.nextin a named variable before changing any pointers — that prevents the classic bug of overwritingself.head.nextfirst and losing the rest of the chain:Before _insert_after_head(node): [head] <───────────────────────> [first_real] After wiring the 4 links: [head] <───> [node] <───> [first_real]class Node: """One cached entry inside the doubly linked recency list.""" def __init__(self, key: int, value: int): # Store `key` alongside `value` so evicting `tail.prev` tells us which dict key to delete. self.key = key self.value = value self.prev: Optional["Node"] = None self.next: Optional["Node"] = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity # key_to_node: maps int key -> its live Node in the doubly linked list for O(1) lookup. self.key_to_node: Dict[int, Node] = {} # Permanent dummy sentinels: `head <-> [most recent] <-> ... <-> [least recent] <-> tail`. # Keeping sentinels at both ends guarantees every real node has non-None `prev` and `next`. self.head = Node(-1, -1) self.tail = Node(-1, -1) self.head.next = self.tail self.tail.prev = self.head def _remove(self, node: Node) -> None: # Splice `node` out of the list by wiring its left and right neighbors directly together. left_neighbor = node.prev right_neighbor = node.next assert left_neighbor is not None and right_neighbor is not None left_neighbor.next = right_neighbor right_neighbor.prev = left_neighbor def _insert_after_head(self, node: Node) -> None: # Place `node` right after `head` (the most-recently-used position). # Save `first_real` before overwriting `head.next` so we do not lose the rest of the list. first_real = self.head.next assert first_real is not None node.prev = self.head node.next = first_real self.head.next = node first_real.prev = nodeImplement `get` and `put`
With
_removeand_insert_after_headready,getandputread like plain English:get(key): Look upnode = self.key_to_node.get(key). Ifnode is None, return-1. Otherwise unlinknode, re-insert it right afterhead, and returnnode.value.put(key, value):- Existing key: Update
existing.value = value, moveexistingright afterhead, and return immediately. - Full cache on a new key: When
len(self.key_to_node) == self.capacity, evictlru_node = self.tail.prevfrom both the linked list andself.key_to_nodebefore inserting. - Insert new key: Create
Node(key, value), store it inself.key_to_node[key], and insert it right afterhead.
- Existing key: Update
Notice we always check
is None/is not Nonerather than truthiness, becausekey = 0andvalue = 0are allowed by the constraints (0 <= key,0 <= value).def get(self, key: int) -> int: # Use `is None` (never truthiness) because key 0 and value 0 are valid cache entries. node = self.key_to_node.get(key) if node is None: return -1 # A cache hit counts as a fresh use: move `node` to the most-recently-used front. self._remove(node) self._insert_after_head(node) return node.value def put(self, key: int, value: int) -> None: # Phase 1: If `key` is already cached, overwrite its value and promote it to the front. existing = self.key_to_node.get(key) if existing is not None: existing.value = value self._remove(existing) self._insert_after_head(existing) return # Phase 2: Adding a brand-new key when full — evict the least recently used node (`tail.prev`) # BEFORE inserting, keeping peak resident count <= capacity. if len(self.key_to_node) == self.capacity: lru_node = self.tail.prev assert lru_node is not None and lru_node is not self.head self._remove(lru_node) del self.key_to_node[lru_node.key] # Phase 3: Create the new node, register it in the map, and place it at the front. new_node = Node(key, value) self.key_to_node[key] = new_node self._insert_after_head(new_node)Replay operations and trace Example 1
lru_cache_operationsinstantiatesLRUCache(capacity)and records each call's output. Here is the complete state trace on Example 1 (capacity = 2):Call Recency list (head -> ... -> tail) Output Why ---------- --------------------------------------- ------ -------------------------------------- put(10,50) head <-> (10:50) <-> tail None insert 10 put(20,60) head <-> (20:60) <-> (10:50) <-> tail None insert 20 at front get(10) head <-> (10:50) <-> (20:60) <-> tail 50 hit! 10 moves to front; 20 is now LRU put(30,70) head <-> (30:70) <-> (10:50) <-> tail None full -> evict tail.prev (20), add 30 get(20) head <-> (30:70) <-> (10:50) <-> tail -1 miss (20 was evicted) get(10) head <-> (10:50) <-> (30:70) <-> tail 50 hit! 10 moves to front; 30 is now LRU put(40,80) head <-> (40:80) <-> (10:50) <-> tail None full -> evict tail.prev (30), add 40 get(30) head <-> (40:80) <-> (10:50) <-> tail -1 miss (30 was evicted) get(10) head <-> (10:50) <-> (40:80) <-> tail 50 hit! 10 moves to frontResult list:
[None, None, 50, None, -1, 50, None, -1, 50].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Node: """One cached entry inside the doubly linked recency list.""" def __init__(self, key: int, value: int): # Store `key` alongside `value` so evicting `tail.prev` tells us which dict key to delete. self.key = key self.value = value self.prev: Optional["Node"] = None self.next: Optional["Node"] = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity # key_to_node: maps int key -> its live Node in the doubly linked list for O(1) lookup. self.key_to_node: Dict[int, Node] = {} # Permanent dummy sentinels: `head <-> [most recent] <-> ... <-> [least recent] <-> tail`. # Keeping sentinels at both ends guarantees every real node has non-None `prev` and `next`. self.head = Node(-1, -1) self.tail = Node(-1, -1) self.head.next = self.tail self.tail.prev = self.head def _remove(self, node: Node) -> None: # Splice `node` out of the list by wiring its left and right neighbors directly together. left_neighbor = node.prev right_neighbor = node.next assert left_neighbor is not None and right_neighbor is not None left_neighbor.next = right_neighbor right_neighbor.prev = left_neighbor def _insert_after_head(self, node: Node) -> None: # Place `node` right after `head` (the most-recently-used position). # Save `first_real` before overwriting `head.next` so we do not lose the rest of the list. first_real = self.head.next assert first_real is not None node.prev = self.head node.next = first_real self.head.next = node first_real.prev = node def get(self, key: int) -> int: # Use `is None` (never truthiness) because key 0 and value 0 are valid cache entries. node = self.key_to_node.get(key) if node is None: return -1 # A cache hit counts as a fresh use: move `node` to the most-recently-used front. self._remove(node) self._insert_after_head(node) return node.value def put(self, key: int, value: int) -> None: # Phase 1: If `key` is already cached, overwrite its value and promote it to the front. existing = self.key_to_node.get(key) if existing is not None: existing.value = value self._remove(existing) self._insert_after_head(existing) return # Phase 2: Adding a brand-new key when full — evict the least recently used node (`tail.prev`) # BEFORE inserting, keeping peak resident count <= capacity. if len(self.key_to_node) == self.capacity: lru_node = self.tail.prev assert lru_node is not None and lru_node is not self.head self._remove(lru_node) del self.key_to_node[lru_node.key] # Phase 3: Create the new node, register it in the map, and place it at the front. new_node = Node(key, value) self.key_to_node[key] = new_node self._insert_after_head(new_node) def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: cache = LRUCache(capacity) # results: records each operation's return value (int or -1 for 'get', None for 'put'). results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "get": results.append(cache.get(args[0])) elif op == "put": cache.put(args[0], args[1]) results.append(None) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine keeping at most capacity reference books in a single stack on your desk: whenever you open a book (get) or add a new book (put), you place it right on top of the stack, and whenever the stack is full and a brand-new book arrives, you clear space by shelving the dusty book at the very bottom. That policy is an LRU (Least Recently Used) cache — a bounded key-value store that evicts whichever item has gone the longest without being read or written. To make both "grab any book instantly" and "move it to the top" run in O(1) time, we pair a hash map (a key-to-node lookup table with O(1) average access) with a doubly linked list (a chain of nodes with prev and next pointers so any node can be unlinked and moved to the front in O(1) pointer updates), capped at both ends by permanent sentinel (dummy) nodes head and tail so we never hit None-pointer special cases.
Why do single-structure solutions fall short? Keeping entries in a plain array or Python list makes moving a hit from the middle to the front shift up to capacity elements (O(capacity) per call, or 10^10 work across 100,000 operations). Conversely, storing (value, last_used_timestamp) in a plain dictionary makes get fast, but evicting the oldest key requires scanning all capacity entries (O(capacity)) or maintaining a lazy heap that accumulates stale entries.
Here is a tiny 5-step trace with capacity = 2:
1. put(10, 50) -> map={10}, list: head <-> [10:50] <-> tail
2. put(20, 60) -> map={10,20}, list: head <-> [20:60] <-> [10:50] <-> tail
3. get(10) -> returns 50, list: head <-> [10:50] <-> [20:60] <-> tail (10 promoted to MRU!)
4. put(30, 70) -> full! evict tail.prev ([20:60]), insert [30:70] at front:
map={10,30}, list: head <-> [30:70] <-> [10:50] <-> tail
5. get(20) -> key 20 not in map -> returns -1
Complexity
- Time:
O(1)average pergetandput(O(n)total acrossnoperations). Each operation performs at most one or two hash-map lookups/updates (O(1)average time) and rewires a constant number ofprev/nextpointers (4assignments to insert,2to unlink). - Space:
O(capacity)for the cache (plusO(n)for the returnedresultslist). Because we evict before inserting whenlen(key_to_node) == capacity, the cache never holds more thancapacityrealNodeobjects andcapacitydictionary entries (plus the2permanent sentinels).
Edge cases
capacity == 1: Overwriting the sole cached key keeps it alive; inserting any distinct key first unlinks that sole node (temporarily leavinghead <-> tail) and then inserts the new node.- Overwriting an existing key when full:
put(5, 99)when key5is already cached updates5's value and promotes5tohead.nextwithout evicting any key. - Cache miss on
get: Returns-1immediately and leaves the recency list untouched. - Zero keys and zero values (
key = 0,value = 0): Valid under0 <= keyand0 <= value; testingnode is Nonerather thanif not nodeavoids treating0as missing. geton an empty cache or empty operation list:getreturns-1cleanly whenhead.next is tail, andoperations = []returns[].
Common mistakes
- Forgetting to promote a key on
get: Treatinggetas read-only lets hot keys drift towardtailand get evicted prematurely (Example 1 fails immediately withoutgetpromotion). - Evicting on an overwrite, or forgetting to refresh recency on an overwrite: Updating an existing key does not increase the key count and must still move that key to the front.
- Storing only
value(and notkey) insideNode: When evictinglru_node = self.tail.prev, you only have the node reference; withoutlru_node.key, you cannot delete its entry fromkey_to_nodeinO(1)time. - Corrupting pointers during
_insert_after_head: Writingself.head.next = nodebefore saving the oldself.head.nextorphans the entire rest of the list. Namingfirst_real = self.head.nextup front prevents this completely. - Updating the list without updating
key_to_node(or vice versa): Leaving an evicted key in the dictionary turns future misses into ghost hits and breakslen(key_to_node) == capacity.
Alternative approaches
collections.OrderedDict(Python standard library): Under the hood,OrderedDictis implemented in C as a hash table plus a doubly linked list withmove_to_end(key)andpopitem(last=False), giving the sameO(1)bounds in ~15 lines. In interviews, however, buildingNodeand the doubly linked list explicitly is almost always what the interviewer wants to see.
Follow-up questions
- How can you make concurrent reads and writes safe across multiple threads without turning a single lock into a bottleneck? Because even
get(key)mutatesprev/nextpointers in the doubly linked list, a reader-writer lock (a lock allowing concurrent readers when state is unchanged) offers no concurrency benefit — everygetandputis a write! Start by wrappinggetandputin a single mutex (mutual exclusion lock,threading.Lock()), which is necessary even in Python because a thread switch mid-_removecan corrupt list pointers. Under high multi-core contention, use lock striping (sharding): partition the cache intoSindependent sub-caches of capacitycapacity / Srouted byhash(key) % S, each protected by its own mutex so threads hitting different shards run in parallel (or adopt an approximate policy like CLOCK that flips an atomic reference bit ongetinstead of relinking pointers). - When access popularity varies sharply across keys, how does LFU eviction compare against LRU, and where does each policy struggle? LFU (Least Frequently Used) evicts the item with the lowest access count rather than the oldest timestamp, so it outperforms LRU when popularity is stable and skewed — especially during a one-time sequential scan of cold keys, which flushes an entire LRU cache ("cache pollution") while LFU protects frequently hit keys. However, pure LFU struggles when traffic patterns shift over time because formerly popular keys keep high historical counts forever ("frequency stagnation") unless counts are periodically decayed. Production caches often combine both signals (such as Window-TinyLFU) and pick the winner by replaying real production access traces to measure hit rate.
- If the cache must warm-start its state after an unexpected process crash, how would you design durable persistence? First confirm whether persistence is worth the latency cost, since an in-memory cache can usually cold-start empty and repopulate from the primary database. If warm recovery is required to prevent a post-crash database stampede, periodically write an atomic snapshot of
(key, value)pairs ordered from least recent to most recent (writing to a temp file and renaming atomically), and append everyputbetween snapshots to an append-only write-ahead log (WAL) on disk with per-record checksums. On restart, replay the latest snapshot followed by valid WAL records; batchingfsync(the OS call that flushes buffered disk writes to durable storage) every few milliseconds trades a tiny window of lost cache updates for lowputlatency, and skippinggetlogging avoids turning every memory read into disk I/O at the cost of approximate post-crash recency order.
Follow-up questions
- How can you make concurrent reads and writes safe across multiple threads without turning a single lock into a bottleneck?
- When access popularity varies sharply across keys, how does LFU eviction compare against LRU, and where does each policy struggle?
- If the cache must warm-start its state after an unexpected process crash, how would you design durable persistence?
Similar questions
- Type-Safe Variant Container with Explicit Lifetime Control
- Kafka Architecture and Exactly-Once Batched Trade Aggregation
- Bounded-Concurrency Task Scheduler for Dependency Graphs
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses