Fixed-Capacity LRU Cache Simulation
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a bounded key-value store of maximum size capacity governed by Least Recently Used (LRU) eviction, executing a stream of "get" and "put" commands and collecting all "get" responses in chronological order.
def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:
The store begins completely empty. At index i, operations[i] is either "get" (paired with arguments[i] == [key]) or "put" (paired with arguments[i] == [key, value]):
"get"([key]):- When
keyis currently cached, promotekeyto most recently used and record its stored value in the output list. - When
keyis absent, record-1in the output list without insertingkeyor altering recency order.
- When
"put"([key, value]):- Produces no output entry.
- When
keyis already cached, overwrite its stored value withvalueand promotekeyto most recently used; no entry is evicted. - When
keyis absent: if the store currently containscapacityentries, first discard whichever entry is least recently used, then insert(key, value)as most recently used.
Inserting a new key, overwriting an existing key, and hitting an existing key on "get" each count as using that key. Return a list[int] containing one result per "get" command.
Examples
Example 1
Input:
capacity = 2
operations = ["put", "put", "get", "put", "get", "put", "get", "get"]
arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [40, 400], [10], [30]]
Output: [100, -1, -1, 300]
After inserting 10 and 20, reading 10 returns 100 and promotes 10 ahead of 20. Inserting 30 evicts 20 (so get(20) returns -1); inserting 40 then evicts 10 (so get(10) returns -1), while get(30) returns 300.
Example 2
Input:
capacity = 2
operations = ["put", "put", "put", "put", "get", "get", "get"]
arguments = [[4, 40], [8, 80], [4, 45], [9, 90], [4], [8], [9]]
Output: [45, -1, 90]
put(4, 45) updates key 4 in place without eviction and refreshes its recency, leaving 8 as least recently used so put(9, 90) evicts 8.
Example 3
Input:
capacity = 1
operations = ["put", "get", "put", "get", "get"]
arguments = [[3, 0], [3], [7, 25], [3], [7]]
Output: [0, -1, 25]
Storing 0 under key 3 is a valid entry, so get(3) returns 0. Because capacity == 1, put(7, 25) evicts key 3 before inserting key 7.
Constraints
1 <= capacity <= 30001 <= len(operations) == len(arguments) <= 2 * 10^50 <= key <= 10^40 <= value <= 10^9- Target
O(1)average time per command.
Step-by-step walkthrough
Understand the cache rules
We need to simulate a fixed-capacity Least Recently Used (LRU) cache across a list of
"get"and"put"commands and return the results of all"get"commands in order:get(key): Ifkeyis in the cache, markkeyas most recently used and return its value (note that a stored value of0is a valid hit, not a miss!). Ifkeyis missing, return-1and leave the cache untouched.put(key, value):- If
keyis already in the cache, overwrite its value and markkeyas most recently used. Nothing is evicted, even if the cache is full. - If
keyis not in the cache and the cache already holdscapacitykeys, evict the least recently used key first, then insert(key, value)as the most recently used key.
- If
Why a plain Python list is too slow
A simple working prototype keeps a dictionary
values[key] = valuealongside a plain Python listorderof keys from oldest to newest:- On a hit or update: call
order.remove(key)andorder.append(key). - On eviction: call
order.pop(0)and delete that key fromvalues.
While easy to write, both
order.remove(key)andorder.pop(0)scan or shift elements across the array, costingO(capacity)time per operation. With2 * 10^5operations andcapacity = 3,000, that reaches roughly6 * 10^8array shifts. To hitO(1)average time per operation, we need a structure that can jump to any key and pull it out of the middle of the recency line without shifting anything else.- On a hit or update: call
Key idea: pair a dictionary with a doubly linked list
We combine two data structures so each covers the other's weakness:
- A hash map (
key_to_nodedict): mapskey -> Nodeso we can locate any key's node inO(1)average time. - A doubly linked list of
Nodes: keeps cached entries in recency order from oldest (left) to newest (right). Because every node stores pointers to both itsprevandnextneighbors, unlinking a node from the middle and splicing it onto the right end rewires just a handful of pointers inO(1)time!
key_to_node dict: 10 ────────┐ 20 ────────┐ v v Doubly linked list: [head] <-> [10: 100] <─────────> [20: 200] <-> [tail] dummy least recently used most recently used dummyTwo small design choices eliminate edge-case bugs:
- Dummy sentinel nodes
headandtail: They permanently cap both ends of the list and never hold user keys. Even when the cache is empty (head <-> tail), every real node always has a non-Noneprevandnextneighbor! - Store
keyinsideNode: When we evicthead.next, readinglru_node.keytells us which key to delete fromkey_to_nodeinO(1)time.
- A hash map (
Code the node and pointer helpers
Let's write the two
O(1)linked-list building blocks:_remove_node(node)bridgesnode.prevandnode.nextdirectly acrossnode._add_to_most_recent(node)splicesnoderight betweentail.prevandtail.
_remove_node(X): [prev_node] <-> [X] <-> [next_node] => [prev_node] <---------> [next_node] _add_to_most_recent(X): [prev_most_recent] <---------> [tail] => [prev_most_recent] <-> [X] <-> [tail]class Node: # Doubly-linked-list node storing (key, value) plus prev/next neighbor pointers. # Storing `key` on the node lets us delete the evicted key from `key_to_node` in O(1). def __init__(self, key: int, value: int): 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 each cached int key -> its live Node in the doubly linked list. self.key_to_node: Dict[int, Node] = {} # Dummy sentinel nodes frame all real entries so list ends are never None: # head <-> [least recent] <-> ... <-> [most recent] <-> tail 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` in O(1) by wiring its left and right neighbors directly together. prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _add_to_most_recent(self, node: Node) -> None: # Splice `node` right before `tail` so it becomes the most recently used entry. prev_most_recent = self.tail.prev prev_most_recent.next = node node.prev = prev_most_recent node.next = self.tail self.tail.prev = nodeCode `get` and `put`
With
_remove_nodeand_add_to_most_recentready, "promoting a node to most recently used" is just_remove_node(node)followed by_add_to_most_recent(node):get(key): Look upnode = self.key_to_node.get(key). Checkif node is None:(neverif not node:orif not value:, because0is a valid value!). On a hit, promotenodeand returnnode.value.put(key, value): Handle the three cases in strict order:- Existing key: update
existing_node.value = value, promoteexisting_node, andreturnimmediately (no eviction!). - Full cache on a new key:
lru_node = self.head.nextis the oldest entry; unlink it and deletelru_node.keyfromself.key_to_node. - Insert new key: create
new_node = Node(key, value), record it inself.key_to_node, and append it right beforetail.
- Existing key: update
def get(self, key: int) -> int: # Phase 1 (Lookup): Check `is None` explicitly because stored value `0` is a valid hit. node = self.key_to_node.get(key) if node is None: return -1 # Phase 2 (Refresh recency): Move the hit node to the most-recent end before returning. self._remove_node(node) self._add_to_most_recent(node) return node.value def put(self, key: int, value: int) -> None: # Case 1: Key already exists -> update value in place and mark most recent (never evict!). existing_node = self.key_to_node.get(key) if existing_node is not None: existing_node.value = value self._remove_node(existing_node) self._add_to_most_recent(existing_node) return # Case 2: New key and cache is at capacity -> evict least recently used node (`head.next`). if len(self.key_to_node) == self.capacity: lru_node = self.head.next self._remove_node(lru_node) del self.key_to_node[lru_node.key] # Case 3: Insert the new key-value node at the most-recent end. new_node = Node(key, value) self.key_to_node[key] = new_node self._add_to_most_recent(new_node)Code the runner and trace Example 1
run_lru_cacheinstantiates a freshLRUCache(capacity)inside the function (so separate calls never leak state into each other), loops overzip(operations, arguments), and collects everygetreturn value.def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]: # Create a fresh cache per call so independent runs never share state. cache = LRUCache(capacity) get_results: List[int] = [] for op, args in zip(operations, arguments): if op == "get": key = args[0] get_results.append(cache.get(key)) elif op == "put": key = args[0] value = args[1] cache.put(key, value) else: raise ValueError(f"unknown operation {op!r}") return get_resultsLet's trace Example 1 (
capacity = 2, showinghead <-> ... <-> tailfrom least recent to most recent):put(10, 100): head <-> [10:100] <-> tail outputs: [] put(20, 200): head <-> [10:100] <-> [20:200] <-> tail outputs: [] get(10): head <-> [20:200] <-> [10:100] <-> tail (10 promoted!) outputs: [100] put(30, 300): full! evict head.next ([20:200]), insert [30:300] head <-> [10:100] <-> [30:300] <-> tail outputs: [100] get(20): miss! list unchanged outputs: [100, -1] put(40, 400): full! evict head.next ([10:100]), insert [40:400] head <-> [30:300] <-> [40:400] <-> tail outputs: [100, -1] get(10): miss! outputs: [100, -1, -1] get(30): head <-> [40:400] <-> [30:300] <-> tail (30 promoted!) outputs: [100, -1, -1, 300]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Node: # Doubly-linked-list node storing (key, value) plus prev/next neighbor pointers. # Storing `key` on the node lets us delete the evicted key from `key_to_node` in O(1). def __init__(self, key: int, value: int): 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 each cached int key -> its live Node in the doubly linked list. self.key_to_node: Dict[int, Node] = {} # Dummy sentinel nodes frame all real entries so list ends are never None: # head <-> [least recent] <-> ... <-> [most recent] <-> tail 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` in O(1) by wiring its left and right neighbors directly together. prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _add_to_most_recent(self, node: Node) -> None: # Splice `node` right before `tail` so it becomes the most recently used entry. prev_most_recent = self.tail.prev prev_most_recent.next = node node.prev = prev_most_recent node.next = self.tail self.tail.prev = node def get(self, key: int) -> int: # Phase 1 (Lookup): Check `is None` explicitly because stored value `0` is a valid hit. node = self.key_to_node.get(key) if node is None: return -1 # Phase 2 (Refresh recency): Move the hit node to the most-recent end before returning. self._remove_node(node) self._add_to_most_recent(node) return node.value def put(self, key: int, value: int) -> None: # Case 1: Key already exists -> update value in place and mark most recent (never evict!). existing_node = self.key_to_node.get(key) if existing_node is not None: existing_node.value = value self._remove_node(existing_node) self._add_to_most_recent(existing_node) return # Case 2: New key and cache is at capacity -> evict least recently used node (`head.next`). if len(self.key_to_node) == self.capacity: lru_node = self.head.next self._remove_node(lru_node) del self.key_to_node[lru_node.key] # Case 3: Insert the new key-value node at the most-recent end. new_node = Node(key, value) self.key_to_node[key] = new_node self._add_to_most_recent(new_node) def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]: # Create a fresh cache per call so independent runs never share state. cache = LRUCache(capacity) get_results: List[int] = [] for op, args in zip(operations, arguments): if op == "get": key = args[0] get_results.append(cache.get(key)) elif op == "put": key = args[0] value = args[1] cache.put(key, value) else: raise ValueError(f"unknown operation {op!r}") return get_results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a narrow desk shelf that holds at most capacity folders. Whenever you read a folder (get hit) or file an updated/new folder (put), you slide that folder to the rightmost end of the shelf; when the shelf is full and a brand-new folder arrives, you evict (discard) whichever folder has drifted all the way to the leftmost end because it has gone untouched the longest (LRU, or Least Recently Used eviction). To do both operations instantaneously, we pair a dictionary (key_to_node, mapping each key to its folder in O(1) average time) with a doubly linked list (a chain of nodes where each node points to both its left prev and right next neighbor so any node can be pulled out and re-inserted in O(1) time), framed by two sentinel (dummy) nodes (head and tail, permanent placeholder nodes at both ends so we never hit None pointers on an empty or 1-item list).
Why do simpler single-structure designs fall short? A dictionary by itself looks up keys in O(1) time, but cannot tell which of 3,000 keys was used longest ago without scanning timestamps in O(capacity) time. Conversely, storing keys in a plain array keeps recency order, but pulling a hit key out of the middle (list.remove) or evicting from index 0 (list.pop(0)) shifts up to capacity elements on every call. Using a singly linked list also fails because unlinking a node requires editing its previous node's next pointer, which you cannot reach in O(1) time without a prev pointer.
Here is a quick trace of the first five commands from Example 1 (capacity = 2):
1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [10:100] <-> [20:200] <-> tail
3. get(10) -> hit (100); move 10 to right -> head <-> [20:200] <-> [10:100] <-> tail
4. put(30, 300) -> full! evict head.next ([20:200]), add [30:300] -> head <-> [10:100] <-> [30:300] <-> tail
5. get(20) -> not in key_to_node -> returns -1 (list unchanged)
Complexity
- Time:
O(1)average per operation,O(q)total forq = len(operations). Everygetorputperforms one or two average-O(1)dictionary operations (get, assignment,del) and rewires a constant number (4to8) of linked-list pointers. - Space:
O(capacity + g), wheregis the number ofgetoperations. At any momentkey_to_nodeand the doubly linked list store at mostcapacitylive entries (plus2sentinel nodes), andget_resultsstores one integer perget.
Edge cases
capacity = 1: Updating the single cached key replaces its value without eviction, while inserting any different key evicts the sole entry first.- Stored value equal to
0(Example 3):0is falsy in Python, so checkingif node is None:ensuresgetreturns0instead of treating it as a-1miss. puton an existing key when full (Example 2): Must overwrite the value and promote the key to most-recent without evictinghead.next.- Missed
get: Returns-1without inserting the key or disturbing the recency order of existing keys. - All
puts or allgets: All-putworkloads return[];getcalls on an empty cache all return-1.
Common mistakes
- Checking capacity before checking whether
keyalready exists input: If the cache is full andput(key, new_val)updates an existing key, evicting first mistakenly deletes the oldest key and leaves the cache one slot under capacity. - Updating
existing_node.valuewithout moving it to the tail: An update counts as a "use"; leaving the node nearheadcauses it to be evicted too early. - Forgetting
del self.key_to_node[lru_node.key]on eviction: Unlinkinglru_nodefrom the list without deleting it from the dictionary leaks memory, inflateslen(self.key_to_node), and causes stale cache hits! - Omitting
keyfromNode: Withoutlru_node.key, finding which dictionary key points tohead.nextrequires anO(capacity)scan of the dictionary. - Storing cache state in a module-level global: Causes keys from one test call to leak into the next call.
Alternative approaches
- Python's
collections.OrderedDict: Built in C on top of this exact hash-table + doubly-linked-list design. Callingcache.move_to_end(key)promotes a key inO(1)time andcache.popitem(last=False)evicts the oldest key inO(1)time. In production PythonOrderedDictis ideal, though in coding interviews writingNodeand pointer helpers explicitly is usually expected. - Hash map + min-heap of
(timestamp, key): Increments a counter on each access and pushes(timestamp, key)onto a heap, skipping outdated timestamps on eviction. Each operation degrades fromO(1)toO(log q)time and accumulates stale entries in memory.
Follow-up questions
- How would you make this cache safe and scalable under concurrent multithreaded reads and writes? Because even a
gethit mutatesprev/nextpointers in the linked list, a read-write lock cannot allow parallelgets safely; the simplest correct design wrapsgetandputin a single mutex (a mutual-exclusion lock allowing one thread at a time). Under high concurrency across many CPU cores, hash sharding (splitting the cache intoSindependent sub-caches of capacitycapacity // S, chosen byhash(key) % S, each with its own mutex) reduces lock contention by a factor ofSwhile approximating global LRU closely. - How could you add per-entry time-to-live (TTL) expiration while keeping lookups fast? A TTL (time-to-live) means each entry becomes invalid after a fixed duration even if the cache is not full: store an
expire_attimestamp on eachNodeand treatget(key)as a miss (unlinking and deleting the node immediately) whenevernow >= node.expire_at. If all entries share the same TTL duration, expiration order matches insertion order; if entries have arbitrary TTLs, combine lazy checks ongetwith either a background cleanup sweep or a min-heap keyed byexpire_atso dead entries do not hog capacity forever. - What data-structure changes are needed to switch the eviction policy to Least Frequently Used (LFU) in O(1) time? LFU (Least Frequently Used) evicts the key with the lowest access count, breaking ties by least recently used. To keep
O(1)time, maintainkey_to_node, an integermin_freq, and afreq_to_listdictionary mapping each frequencyfto its own doubly linked list of nodes: touching a key moves its node fromfreq_to_list[f]to the most-recent end offreq_to_list[f + 1](incrementingmin_freqiff == min_freqandfreq_to_list[f]just became empty), while inserting a new key evicts the oldest node fromfreq_to_list[min_freq]and resetsmin_freq = 1.
Follow-up questions
- How would you make this cache safe and scalable under concurrent multithreaded reads and writes?
- How could you add per-entry time-to-live (TTL) expiration while keeping lookups fast?
- What data-structure changes are needed to switch the eviction policy to Least Frequently Used (LFU) in O(1) time?
Similar questions
- Signed Big-Integer String Addition
- Busiest Conference Room Under Delayed Scheduling
- Reconstruct Binary Tree from Parent-Child Edges
- Time-Ordered Task Queue with Cancellations
- Strict Addition and Subtraction Expression Evaluator
- Largest Integer Strictly Under N From Permitted Digits
More ByteDance interview questions
- Batched Multi-Head Attention Forward Pass Medium
- Platform PM Walkthrough: Flagship Projects, Trade-Offs, and Impact Medium
- Course Completion with Prerequisites Hard Pro
- Deriving Alphabet Order from Sorted Words Medium Pro
- Course Completion Feasibility with Prerequisites Medium Pro
- Sum of Root-to-Leaf Path Numbers Medium Pro
- Contiguous House Blocks After Removals Medium Pro
- Hardest Engineering Project and Technical Leadership Medium Pro
- Consolidate Overlapping Closed Intervals Medium Pro
- Career Narrative and Role Alignment for TikTok PM Medium Pro