Constant-Time LRU Cache with Fixed Capacity
Easy · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
High-throughput backend services routinely keep a bounded RAM cache ahead of slower persistent storage so repeated lookups avoid network and disk round-trips. Because fast memory is finite, caching introduces core engineering trade-offs between read speed, RAM footprint, staleness relative to the backing store, and per-request bookkeeping.
Design a bounded Least Recently Used (LRU) cache supporting constant-time reads and writes, and expose it through the driver function:
def lru_cache_operations(
capacity: int,
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
Instantiate a fresh cache of size capacity and execute operations[i] with arguments[i] for each step i:
"get"with[key]: Look upkeyin the cache. When present, promotekeyto be the most recently accessed entry and record its mapped integer in the output list. When absent, leave cache state untouched and record-1."put"with[key, value]: Storevalueunderkeyand recordNonein the output list.- If
keyis already cached, overwrite its value in place and promotekeyto most recently accessed without removing any entry. - If
keyis new and the cache already holdscapacityentries, first discard whichever cached entry has gone untouched for the longest time, then insert(key, value)as most recently accessed.
- If
Every "get" and "put" step must execute in O(1) average time.
Examples
Example 1
Input:
capacity = 2
operations = ["put", "put", "get", "put", "get", "put", "get", "get"]
arguments = [[10, 50], [20, 80], [10], [30, 90], [20], [40, 70], [10], [40]]
Output:
[None, None, 50, None, -1, None, -1, 70]
Walk-through:
- put(10, 50) and put(20, 80) fill both slots (20 is newest, 10 is oldest).
- get(10) returns 50 and promotes key 10, making key 20 the oldest entry.
- put(30, 90) exceeds capacity 2, so key 20 is evicted; a subsequent get(20) returns -1.
- put(40, 70) evicts key 10 (now oldest), so get(10) returns -1 while get(40) returns 70.
Example 2
Input:
capacity = 2
operations = ["put", "put", "put", "put", "get", "get"]
arguments = [[5, 100], [8, 200], [5, 150], [9, 300], [5], [8]]
Output:
[None, None, None, None, 150, -1]
Walk-through:
- After put(5, 100) and put(8, 200), key 5 is oldest.
- put(5, 150) updates key 5 in place and refreshes its recency without evicting anything, leaving key 8 as oldest.
- put(9, 300) therefore evicts key 8, so get(5) yields 150 and get(8) yields -1.
Constraints
1 <= capacity <= 30000 <= len(operations) == len(arguments) <= 2 * 10^5- Each
operations[i]is either"get"(with[key]) or"put"(with[key, value]). 0 <= key <= 10^40 <= value <= 10^5
Step-by-step walkthrough
Restate the problem, caching trade-offs, and judge format
In high-throughput backend services, placing an in-memory cache ahead of a slower persistent store turns millisecond disk or network reads into sub-microsecond RAM lookups. That speedup carries three practical trade-offs:
- Memory bound & eviction: Fast RAM is limited, so once the cache reaches
capacitykeys, inserting a brand-new key must discard an existing one—here the Least Recently Used (LRU) key (the entry untouched for the longest time). - Bookkeeping overhead: Even a read (
get) mutates internal recency state so the cache records that the key was just accessed. - Freshness / consistency: If another service modifies the backing database directly, cached values can drift out of date unless an invalidation or expiration policy is paired with the cache.
We need an
LRUCache(capacity)class where bothget(key)andput(key, value)run inO(1)average time, wrapped bylru_cache_operations(capacity, operations, arguments)which replays"get"and"put"calls and returns[result_0, result_1, ...](Nonefor"put", mapped value or-1for"get").- Memory bound & eviction: Fast RAM is limited, so once the cache reaches
Why a dictionary plus a plain list is too slow
A natural first attempt keeps
values = {}forO(1)key lookups and a Python listorder = [...]of keys ordered from oldest to newest:- On a
get(key)hit: callorder.remove(key)andorder.append(key). - On an eviction: call
order.pop(0).
That logic is completely accurate (and makes a great brute-force test oracle), but
order.remove(key)scans and shifts elements in the list, andorder.pop(0)shifts every remaining element left by one index. Each call costsO(capacity)time instead ofO(1).- On a
Key idea: hash map pointing directly into a doubly linked list
To get
O(1)for both lookup and reordering, we combine two data structures so each covers the other's weakness:- A hash map (
self.nodes: dict[int, Node]) maps eachkeydirectly to itsNodeobject inO(1)average time—no scanning required to find a node in the middle of the list. - A doubly linked list (a chain of nodes where each node holds pointers
prevandnextto both neighbors) orders entries from most recently used (right afterhead) to least recently used (right beforetail). Given a direct pointer tonode, unlinking it from its two neighbors takesO(1)pointer assignments!
Hash map (self.nodes): key 10 --------------------\ key 30 ----\ \ v v [head] <---> [30: 90] <---> [10: 50] <---> [tail] ^MRU^ ^LRU^ (most recent) (evict next!)Notice one crucial detail: each
Nodestores bothkeyandvalue. When the cache is full, we find the victim atself.tail.previnO(1)time—and readinglru_node.keytells us which key to delete fromself.nodes!- A hash map (
Sentinel nodes and the two O(1) pointer helpers
Empty lists and 1-element lists normally require messy
if node.prev is Nonebranches. Placing two permanent dummy sentinel nodesheadandtailat the boundaries (head <-> tailwhen empty) guarantees every real cache node always sits strictly between two real neighbor objects!Every recency change in the entire cache reduces to two tiny
O(1)helpers:_remove_node(node): Before: [prev_node] <---> [node] <---> [next_node] After: [prev_node] <----------------> [next_node] _add_after_head(node): Before: [head] <----------------> [old_first] After: [head] <---> [node] <---> [old_first]Saving
prev_node,next_node, andold_firstinto named variables before changing any links makes the four pointer assignments impossible to tangle:class Node: """Doubly linked list node storing one cache entry (key, value) and neighbor pointers.""" def __init__(self, key: int, value: int): # We store `key` alongside `value` so evicting tail.prev lets us delete `nodes[key]` in O(1). self.key = key self.value = value self.prev: Optional["Node"] = None self.next: Optional["Node"] = None class LRUCache: """Fixed-capacity Least Recently Used cache supporting O(1) average get and put. - nodes: dict mapping key -> Node for O(1) lookup. - head <-> ... <-> tail: doubly linked list ordered from most recent (after head) to least recent (before tail). """ def __init__(self, capacity: int): self.capacity = capacity self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes bound both ends of the list: head <-> tail when empty. # Every real node always sits between two non-None nodes, avoiding edge-case checks. self.head = Node(-1, -1) self.tail = Node(-1, -1) self.head.next = self.tail self.tail.prev = self.head def _remove_node(self, node: Node) -> None: """Unlink `node` from its current position in the doubly linked list in O(1).""" prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _add_after_head(self, node: Node) -> None: """Insert `node` immediately after `head` (marking it most recently used) in O(1).""" # Save old_first before rewiring so pointer assignment order cannot lose the rest of the list. old_first = self.head.next self.head.next = node node.prev = self.head node.next = old_first old_first.prev = node def _move_to_front(self, node: Node) -> None: """Refresh an existing node's recency by moving it right after `head`.""" self._remove_node(node) self._add_after_head(node)Implement `get`: lookup and refresh recency
On
get(key):- If
keyis not inself.nodes, return-1without modifying anything. - If
keyis present, move its node right afterhead(because reading counts as using!) and returnnode.value.
Always check
if node is Nonerather than falsiness (if not val):0is a valid value (0 <= value <= 10^5) and must return0, not-1!def get(self, key: int) -> int: # Check `is None` explicitly because stored value 0 is valid and must not be treated as missing. node = self.nodes.get(key) if node is None: return -1 self._move_to_front(node) return node.value- If
Implement `put`: in-place update vs eviction + insert
put(key, value)has two distinct paths:- Key already exists: Update
existing_node.value = value, call_move_to_front(existing_node), and return immediately. Because no new key was added, we never evict on an update—even iflen(self.nodes) == self.capacity. - Key is brand new: If
len(self.nodes) == self.capacity, first evictlru_node = self.tail.prevby unlinking it from the list and deletingself.nodes[lru_node.key]. Evicting before inserting ensurescapacity = 1cleanly empties the lone slot before adding the new node. Then createnew_node, store it inself.nodes[key], and add it right afterhead.
def put(self, key: int, value: int) -> None: existing_node = self.nodes.get(key) if existing_node is not None: # Phase 1 (update): overwrite value and refresh recency; key count does not grow, so no eviction. existing_node.value = value self._move_to_front(existing_node) return # Phase 2 (evict if full): evict BEFORE inserting so capacity = 1 works cleanly. if len(self.nodes) == self.capacity: lru_node = self.tail.prev self._remove_node(lru_node) del self.nodes[lru_node.key] # Phase 3 (insert): record new node in the map and place it at the most-recent front. new_node = Node(key, value) self.nodes[key] = new_node self._add_after_head(new_node)- Key already exists: Update
Wire up the driver and trace Example 1
lru_cache_operationsinstantiatesLRUCache(capacity)and steps through(op, args)pairs. Let's trace Example 1 withcapacity = 2:Start: head <-> tail nodes={} out=[] put(10, 50): head <-> [10:50] <-> tail nodes={10} -> None put(20, 80): head <-> [20:80] <-> [10:50] <-> tail nodes={10, 20} -> None get(10): head <-> [10:50] <-> [20:80] <-> tail (10 moves to front!) -> 50 put(30, 90): full! evict tail.prev = [20:80], del nodes[20] head <-> [30:90] <-> [10:50] <-> tail nodes={10, 30} -> None get(20): miss! list unchanged nodes={10, 30} -> -1 put(40, 70): full! evict tail.prev = [10:50], del nodes[10] head <-> [40:70] <-> [30:90] <-> tail nodes={30, 40} -> None get(10): miss! -> -1 get(40): head <-> [40:70] <-> [30:90] <-> tail (40 stays at front!) -> 70Collected output:
[None, None, 50, None, -1, None, -1, 70], matching Example 1!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Node: """Doubly linked list node storing one cache entry (key, value) and neighbor pointers.""" def __init__(self, key: int, value: int): # We store `key` alongside `value` so evicting tail.prev lets us delete `nodes[key]` in O(1). self.key = key self.value = value self.prev: Optional["Node"] = None self.next: Optional["Node"] = None class LRUCache: """Fixed-capacity Least Recently Used cache supporting O(1) average get and put. - nodes: dict mapping key -> Node for O(1) lookup. - head <-> ... <-> tail: doubly linked list ordered from most recent (after head) to least recent (before tail). """ def __init__(self, capacity: int): self.capacity = capacity self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes bound both ends of the list: head <-> tail when empty. # Every real node always sits between two non-None nodes, avoiding edge-case checks. self.head = Node(-1, -1) self.tail = Node(-1, -1) self.head.next = self.tail self.tail.prev = self.head def _remove_node(self, node: Node) -> None: """Unlink `node` from its current position in the doubly linked list in O(1).""" prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _add_after_head(self, node: Node) -> None: """Insert `node` immediately after `head` (marking it most recently used) in O(1).""" # Save old_first before rewiring so pointer assignment order cannot lose the rest of the list. old_first = self.head.next self.head.next = node node.prev = self.head node.next = old_first old_first.prev = node def _move_to_front(self, node: Node) -> None: """Refresh an existing node's recency by moving it right after `head`.""" self._remove_node(node) self._add_after_head(node) def get(self, key: int) -> int: # Check `is None` explicitly because stored value 0 is valid and must not be treated as missing. node = self.nodes.get(key) if node is None: return -1 self._move_to_front(node) return node.value def put(self, key: int, value: int) -> None: existing_node = self.nodes.get(key) if existing_node is not None: # Phase 1 (update): overwrite value and refresh recency; key count does not grow, so no eviction. existing_node.value = value self._move_to_front(existing_node) return # Phase 2 (evict if full): evict BEFORE inserting so capacity = 1 works cleanly. if len(self.nodes) == self.capacity: lru_node = self.tail.prev self._remove_node(lru_node) del self.nodes[lru_node.key] # Phase 3 (insert): record new node in the map and place it at the most-recent front. new_node = Node(key, value) self.nodes[key] = new_node self._add_after_head(new_node) def lru_cache_operations( capacity: int, operations: List[str], arguments: List[List[int]], ) -> List[Optional[int]]: """Replay a sequence of get/put operations against LRUCache and collect return values.""" cache = LRUCache(capacity) 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 a small stack of at most capacity reference folders on your desk so you don't have to walk down to a slow basement archive (a disk database or remote storage service). Every time you read a folder (get) or add/update one (put), you place that folder right on top of the stack; when the desk is full and a brand-new folder arrives, you discard the folder sitting on the very bottom—the Least Recently Used (LRU) item. To both locate any folder instantly and pull a folder out of the middle of the stack without shuffling the others, we combine a hash map (a key-value lookup table with O(1) average access) that points directly to each folder with a doubly linked list (a chain of nodes where every node points to both its prev and next neighbor).
A naive design that tracks key order in a plain Python list has to search and shift elements whenever a key moves to the front (list.remove) or gets evicted (list.pop(0)), costing O(capacity) time per operation. Alternatively, storing last-used timestamps in a dictionary makes updates O(1), but finding the minimum timestamp during eviction still scans all capacity entries. Pairing nodes[key] -> Node with dummy sentinel nodes (head and tail boundary markers that never hold real data so every real node always has two non-None neighbors) makes every step constant-time.
Let's trace capacity = 2 on the first four calls of Example 1:
put(10, 50): list becomeshead <-> [10:50] <-> tail,nodes = {10: [10:50]}.put(20, 80):[20:80]goes right afterhead, givinghead <-> [20:80] <-> [10:50] <-> tail.get(10):nodes[10]jumps directly to[10:50], unlinks it, and reinserts it afterhead, givinghead <-> [10:50] <-> [20:80] <-> tailand returning50.put(30, 90): cache is full (len(nodes) == 2), so we evicttail.prev([20:80]), delete key20fromnodes, and insert[30:90]afterhead, leavinghead <-> [30:90] <-> [10:50] <-> tail.
Complexity
- Time:
O(1)average pergetandput(O(q)total forqoperations). Eachgetperforms one hash-map lookup (O(1)average) and at most six pointer reassignments to unlink a node and reinsert it afterhead. Eachputperforms one hash-map lookup, at most one hash-map deletion + insertion (O(1)average), and constant-time pointer updates attail.prevandhead.next. - Space:
O(capacity)for the cache (O(q)for the driver's output list). Because we evict whenever a new key would pushlen(self.nodes)pastcapacity, the hash map and doubly linked list hold at mostcapacityentries (plus 2 fixed sentinel nodes) at all times.
Edge cases
capacity = 1: Every new key immediately evicts the lone existing key (tail.prev, which is alsohead.next) before inserting the new node; updating the same key overwrites its value in place without evicting.- Updating an existing key when the cache is full:
puthits theexisting_node is not Nonebranch first, refreshes its value and recency, and returns without evicting anything. geton a missing key: Returns-1immediately without inserting a placeholder or disturbing the recency order of existing keys.- Key
0or value0: Both0key and0value are valid under the constraints (0 <= key,0 <= value). Checkingif node is Noneavoids falsy-value bugs likereturn cache_dict.get(key) or -1. - Sequential scan larger than
capacity: Inserting10,000distinct keys into a cache of capacity3,000evicts each older key in FIFO order, keeping only the latest3,000keys and bounding memory strictly to3,000nodes.
Common mistakes
- Forgetting to move a key to the front on
get: Reading a key counts as using it; leaving it neartailcauses a frequently read key to be evicted prematurely. - Evicting when
putupdates an existing key: Checkingif len(self.nodes) == self.capacitybefore checkingif key in self.nodeswrongly deletes the oldest key when updating an existing key in a full cache. - Storing only
value(and notkey) insideNode: When evictinglru_node = self.tail.prev, you needlru_node.keyto rundel self.nodes[lru_node.key]inO(1)time. Forgettingdel self.nodes[...]leaks memory, serves stale evicted keys on futuregets, and stopslen(self.nodes) == self.capacityfrom ever triggering again! - Using a singly linked list: Even with a hash map pointing directly to
node, unlinkingnoderequires updatingnode.prev.next, which takesO(capacity)to find in a singly linked list. - Overwriting
self.head.nextbefore reading it in_add_after_head: Savingold_first = self.head.nextfirst avoids severing the rest of the list.
Alternative approaches
collections.OrderedDict(O(1)average time,O(capacity)space): Python's standardOrderedDictalready pairs a hash table with an internal doubly linked list:move_to_end(key)refreshes recency inO(1)andpopitem(last=False)evicts the oldest entry inO(1). It is idiomatic in production Python, though interviewers almost always ask you to buildNode+LRUCachedirectly to test pointer manipulation.
Follow-up questions
- How can you make concurrent reads and writes thread-safe without turning a single global lock into a throughput bottleneck? Because
getmutates the doubly linked list on every cache hit, a reader-writer lock (a lock allowing multiple concurrent readers when state is unchanged) does not help—every hit behaves like a write! Wrapping the whole cache in a single mutex (a mutual-exclusion lock allowing only one thread at a time) is thread-safe but serializes all threads under heavy load. To cut contention dramatically, use sharding (also called lock striping: splitting the cache intoSindependent sub-caches of capacitycapacity / Sselected byhash(key) % S, each with its own mutex and doubly linked list), or buffer read-recency updates in lock-free ring buffers and drain them in batches, as high-throughput caches like Caffeine do. - When external services write directly to the backing database, what invalidation or expiration strategy keeps cached entries from staying stale? Write-through (updating both cache and database synchronously on writes) and write-around (writing straight to the database and bypassing or evicting from the local cache) only see writes performed by this service—writes made directly to the database by other services still leave our cache stale! Therefore, you must combine a TTL (Time-To-Live) expiration (an upper time limit after which cached entries automatically expire, bounding maximum staleness) with event-driven invalidation via change-data-capture (CDC) (streaming committed database row changes over a message bus like Kafka so cache instances immediately delete modified keys). For strict invariants where even millisecond staleness is unsafe, bypass the cache or validate a row version number against the primary store.
- What changes if you replace LRU with LFU (Least Frequently Used), and what are the memory and workload trade-offs between frequency and recency? LFU (Least Frequently Used) evicts the key with the lowest access count (breaking ties by LRU), which protects hot keys when a large one-time batch scan sweeps through the cache—a workload that causes cache pollution in LRU (evicting genuinely popular keys to make room for scan items that are never read again). However, pure LFU suffers from "frequency hangover": a key accessed thousands of times yesterday can stay stuck in the cache long after nobody needs it unless counts periodically decay, and
O(1)LFU requires noticeably heavier bookkeeping (a map from key to node, a map from each frequency count to its own doubly linked list, and amin_freqtracker). LRU uses half the metadata and adapts immediately when the working set shifts.
Follow-up questions
- How can you make concurrent reads and writes thread-safe without turning a single global lock into a throughput bottleneck?
- When external services write directly to the backing database, what invalidation or expiration strategy keeps cached entries from staying stale?
- What changes if you replace LRU with LFU (Least Frequently Used), and what are the memory and workload trade-offs between frequency and recency?
Similar questions
- Maximum Floored Student Average Across Streaming, Disk, and Parallel Execution
- Room Allocation with Custom Sorting, Streams, and Append-Only Logs
- Product Judgment, Learning Agility, and Setback Recovery
- Achievable Ranks When Reversing a 4x4 Matrix Product
- Maximum Rocks Along an Up-Right Grid Path
- Decision Tree Split Selection and MSE Gradient Update
More Goldman Sachs interview questions
- Rainwater Trapped Across Unit-Width Elevation Columns Medium
- Highest Frequency Within Increment Budget Medium
- Strictly Rising Subarrays and Three-Group Partition Score Medium Pro
- Real-Time Telemetry Dashboard: Range Rollups and Watermarking Medium Pro
- Monte Carlo Estimation of Pi Using Cardboard and a Six-Sided Die Medium Pro
- Largest Component Root in Parent-Link Forest Medium Pro
- Translating Equity Signals into Portfolios: Validation, Regimes, and Information Theory Medium Pro
- Maximum Floored Student Average Across Streaming, Disk, and Parallel Execution Medium Pro
- Cheapest Directed Tour Across All Locations Medium Pro
- Room Allocation with Custom Sorting, Streams, and Append-Only Logs Medium Pro