Fixed-Capacity LRU Cache
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a bounded key-value store that evicts its least recently used (LRU) entry whenever space runs out, exposed through the batch runner lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]].
Create a single cache instance configured with maximum entry count capacity, execute each (operations[i], arguments[i]) pair in order, and record one output per step:
"get"with[key]:- If
keyis present in the cache, markkeyas the most recently accessed entry and output its stored integer value. - If
keyis absent, output-1and leave the cache contents and recency order untouched.
- If
"put"with[key, value](always outputsNone):- If
capacity <= 0, the cache cannot retain any items, so nothing is stored. - If
keyis already present, overwrite its value withvalueand markkeyas most recently accessed without evicting any entry. - If
keyis new and the cache currently containscapacityitems, evict the least recently accessed key—the cached key that has gone the longest without a successful"get"or"put"—before inserting(key, value)as most recently accessed.
- If
Both "get" and "put" must run in O(1) average time.
Examples
Example 1
- Input:
capacity = 2operations = ["put", "put", "get", "put", "get", "get"]arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [10]]
- Output:
[None, None, 100, None, -1, 100] - Explanation: After inserting
10 -> 100and20 -> 200, callingget(10)returns100and refreshes key10, making key20the oldest untouched entry. Inserting30 -> 300into the full cache therefore evicts20, soget(20)returns-1whileget(10)still returns100.
Example 2
- Input:
capacity = 2operations = ["put", "put", "put", "put", "get", "get"]arguments = [[4, 40], [5, 50], [4, 45], [6, 60], [5], [4]]
- Output:
[None, None, None, None, -1, 45] - Explanation: Writing
put(4, 45)updates key4in place without evicting key5, and promotes key4ahead of key5. The subsequentput(6, 60)then evicts key5, leaving keys6and4(45).
Example 3
- Input:
capacity = 0operations = ["put", "get"]arguments = [[7, 70], [7]]
- Output:
[None, -1] - Explanation: Because
capacityis0,put(7, 70)stores nothing andget(7)misses with-1.
Constraints
0 <= capacity <= 5 * 10^40 <= len(operations) == len(arguments) <= 10^5- Each
operations[i]is either"get"(with[key]) or"put"(with[key, value]). -10^9 <= key, value <= 10^9- Target time complexity:
O(1)average per operation (O(m)acrossmoperations). - Target auxiliary cache space:
O(max(0, capacity)).
Step-by-step walkthrough
Restate the problem
We need to build a bounded least-recently-used (LRU) cache holding up to
capacitykey-value pairs and supporting two operations in averageO(1)time:get(key)returns the integer stored underkey, or-1whenkeyis absent. Every hit counts as an access, promotingkeyto most recently used.put(key, value)storesvalueunderkeyand markskeyas most recently used. Ifkeyalready exists, its value is updated in place without evicting any item. Ifkeyis brand new and the cache is already atcapacity, we first evict the least recently used item (the one untouched longest).
The batch function
lru_cache(capacity, operations, arguments)runs all calls on one cache instance and returns one element per call: the integer result forget, andNoneforput. Whencapacity <= 0(as in Example 3), the cache cannot store anything, soputis a no-op and everygetreturns-1.Why a single list or dictionary is not enough
Suppose we start with the simplest possible design: a plain Python list of
[key, value]pairs ordered from least recently used at index0to most recently used at the end.- On
get(key), we scan the list to findkey, pop it from the middle, and append it to the end. - On
put(key, value), we scan to remove any old copy, append[key, value], andpop(0)iflen > capacity.
This brute force is easy to reason about, so it makes a great test oracle, yet both scanning for a key and popping from the front or middle shift up to
capacityelements — costingO(capacity)per call instead ofO(1).On the flip side, a plain Python
dictfindskeyin averageO(1)time, yet if we only storekey -> value(even with a timestamp), evicting the oldest entry requires scanning the dictionary (O(capacity)) or maintaining a heap (O(log capacity)). Notice that we have two separate jobs:- Jump directly to any key in
O(1)time. - Pull an item out of the middle, push it to the front, or drop the back item in
O(1)time.
- On
Key idea: pair a hash map with a doubly linked list
We get
O(1)for both jobs by letting a hash map (dict) and a doubly linked list work together:- Doubly linked list in recency order: Every cache entry lives in a node with
prevandnextpointers to both neighbors. Because a node already knows its left and right neighbors, detaching it from the middle or inserting it at the front only updates a handful of pointers inO(1)time — zero shifting. - Hash map
key -> Node: Instead of walking the list to find a key,self.nodes[key]jumps straight to that node in averageO(1)time. - Store
keyinsideNodetoo: When the cache is full, we find the victim at the back of the list (tail.prev). Storingkeyon that node tells us which entry to delete fromself.nodeswithout searching the map. - Two dummy sentinel nodes (
headandtail): We keep a permanent fakeheadat the front and faketailat the back. Every real entry sits strictly between them, sonode.prevandnode.nextare neverNone, eliminating empty-list and boundaryifbranches.
Hash map (self.nodes): 10 ──► [key=10, val=100] 20 ──► [key=20, val=200] Doubly linked list (most recent on the left, least recent on the right): [head] ◄──► [key=20, val=200] ◄──► [key=10, val=100] ◄──► [tail] ▲ ▲ head.next (MRU) tail.prev (LRU victim)- Doubly linked list in recency order: Every cache entry lives in a node with
Code the node and O(1) list helpers
Every recency change boils down to two tiny pointer helpers:
_unlink(node)bridgesnode's left neighbor (prev_node) and right neighbor (next_node) directly to each other, liftingnodeout of the chain._push_front(node)splicesnoderight betweenself.headandfirst_real = self.head.next. Savingfirst_realin a variable first makes the pointer assignments crystal clear and order-independent.
_unlink(X): Before: [prev_node] ◄──► [X] ◄──► [next_node] After: [prev_node] ◄───────────► [next_node] _push_front(X): Before: [head] ◄────────────────► [first_real] After: [head] ◄──► [X] ◄───────► [first_real]from typing import Any, Dict, List, Optional, Set, Tuple class Node: def __init__(self, key: int, value: int): # Store `key` alongside `value` so when we evict `tail.prev` from the list, # we immediately know which key to delete from `self.nodes` in O(1) time. 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 # nodes: dict mapping key -> Node for O(1) average lookup, e.g. {10: Node(10, 100)} self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes permanently bookend the doubly linked list: # head <-> [most recently used ... least recently used] <-> tail self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def _unlink(self, node: Node) -> None: # Detach `node` by connecting its left and right neighbors directly to each other. # Sentinels guarantee `node.prev` and `node.next` are never None for real entries. prev_node = node.prev next_node = node.next assert prev_node is not None and next_node is not None prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: Node) -> None: # Insert `node` right after `head`, marking it as the most recently used entry. 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 = nodeCode get: promote on hit, leave untouched on miss
When
keyis missing fromself.nodes, we return-1immediately — nothing is inserted and no other key's recency changes. Whenkeyis found, reading it counts as using it, so we_unlinkits node and_push_frontit before returningnode.value.def get(self, key: int) -> int: # Cache miss: return -1 and leave recency order completely unchanged. if key not in self.nodes: return -1 # Cache hit: promote the accessed node to the front before returning its value. node = self.nodes[key] self._unlink(node) self._push_front(node) return node.valueCode put: check capacity, update, evict, then insert
In
put(key, value), checking the four phases in exact order avoids two subtle bugs:- Non-positive capacity (
capacity <= 0): Return right away. Without this guard, an empty cache withcapacity = 0satisfieslen(self.nodes) == self.capacity(0 == 0), andself.tail.prevwould try to unlink theheadsentinel! - Existing key (
key in self.nodes): Updatenode.value, movenodeto the front, and return. Doing this before the capacity check guarantees that overwriting an existing key in a full cache never evicts another key (as in Example 2). - Full cache (
len(self.nodes) == self.capacity): Only reached for a brand-new key. Evictlru_node = self.tail.prevfrom both the linked list andself.nodes. - Insert new key: Create
Node(key, value), record it inself.nodes, and push it to the front.
def put(self, key: int, value: int) -> None: # Phase 1: Guard capacity <= 0 first. Otherwise an empty cache has # len(self.nodes) == 0 == capacity and would try to evict the `head` sentinel. if self.capacity <= 0: return # Phase 2: Existing key — update in place and promote to most recent. # Checking this before eviction ensures an overwrite in a full cache evicts nothing. if key in self.nodes: node = self.nodes[key] node.value = value self._unlink(node) self._push_front(node) return # Phase 3: New key in a full cache — evict `tail.prev` (the least recently used node). if len(self.nodes) == self.capacity: lru_node = self.tail.prev assert lru_node is not None self._unlink(lru_node) del self.nodes[lru_node.key] # Phase 4: Insert the new entry into both the hash map and the front of the list. new_node = Node(key, value) self.nodes[key] = new_node self._push_front(new_node)- Non-positive capacity (
Walk through Example 1 and code the judge driver
The driver
lru_cachecreates oneLRUCache(capacity), loops overzip(operations, arguments), and appends either the return value ofgetorNoneforput.Let's trace Example 1 with
capacity = 2:Call Output List (head <-> MRU ... LRU <-> tail) Map keys put(10, 100) None head <-> (10:100) <-> tail {10} put(20, 200) None head <-> (20:200) <-> (10:100) <-> tail {10, 20} get(10) 100 head <-> (10:100) <-> (20:200) <-> tail {10, 20} <- 10 promoted! put(30, 300) None head <-> (30:300) <-> (10:100) <-> tail {10, 30} <- tail.prev (20) evicted get(20) -1 head <-> (30:300) <-> (10:100) <-> tail {10, 30} <- miss changes nothing get(10) 100 head <-> (10:100) <-> (30:300) <-> tail {10, 30}Notice how
get(10)on step 3 rescued key10by promoting it ahead of key20, soput(30, 300)evicted key20instead. The collected outputs are[None, None, 100, None, -1, 100].def lru_cache( capacity: int, operations: List[str], arguments: List[List[int]], ) -> List[Optional[int]]: # Replay each operation on a single LRUCache instance and collect one output per call. cache = LRUCache(capacity) results: List[Optional[int]] = [] for operation, args in zip(operations, arguments): if operation == "get": key = args[0] results.append(cache.get(key)) elif operation == "put": key = args[0] value = args[1] cache.put(key, value) results.append(None) else: raise ValueError(f"unknown operation: {operation}") return resultsComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Node: def __init__(self, key: int, value: int): # Store `key` alongside `value` so when we evict `tail.prev` from the list, # we immediately know which key to delete from `self.nodes` in O(1) time. 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 # nodes: dict mapping key -> Node for O(1) average lookup, e.g. {10: Node(10, 100)} self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes permanently bookend the doubly linked list: # head <-> [most recently used ... least recently used] <-> tail self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head def _unlink(self, node: Node) -> None: # Detach `node` by connecting its left and right neighbors directly to each other. # Sentinels guarantee `node.prev` and `node.next` are never None for real entries. prev_node = node.prev next_node = node.next assert prev_node is not None and next_node is not None prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: Node) -> None: # Insert `node` right after `head`, marking it as the most recently used entry. 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: # Cache miss: return -1 and leave recency order completely unchanged. if key not in self.nodes: return -1 # Cache hit: promote the accessed node to the front before returning its value. node = self.nodes[key] self._unlink(node) self._push_front(node) return node.value def put(self, key: int, value: int) -> None: # Phase 1: Guard capacity <= 0 first. Otherwise an empty cache has # len(self.nodes) == 0 == capacity and would try to evict the `head` sentinel. if self.capacity <= 0: return # Phase 2: Existing key — update in place and promote to most recent. # Checking this before eviction ensures an overwrite in a full cache evicts nothing. if key in self.nodes: node = self.nodes[key] node.value = value self._unlink(node) self._push_front(node) return # Phase 3: New key in a full cache — evict `tail.prev` (the least recently used node). if len(self.nodes) == self.capacity: lru_node = self.tail.prev assert lru_node is not None self._unlink(lru_node) del self.nodes[lru_node.key] # Phase 4: Insert the new entry into both the hash map and the front of the list. new_node = Node(key, value) self.nodes[key] = new_node self._push_front(new_node) def lru_cache( capacity: int, operations: List[str], arguments: List[List[int]], ) -> List[Optional[int]]: # Replay each operation on a single LRUCache instance and collect one output per call. cache = LRUCache(capacity) results: List[Optional[int]] = [] for operation, args in zip(operations, arguments): if operation == "get": key = args[0] results.append(cache.get(key)) elif operation == "put": key = args[0] value = args[1] cache.put(key, value) results.append(None) else: raise ValueError(f"unknown operation: {operation}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a small desk shelf that holds at most capacity folders. Every time you read a folder (get) or place/update one (put), you slide that folder to the leftmost spot on the shelf. Folders you haven't touched in a while naturally drift toward the rightmost end, so when the shelf is full and a new folder arrives, the one at the far right is always the least recently used (LRU) entry and gets tossed out. To make both lookup and reordering instant even for 50,000 folders, we combine a hash map (a key-value lookup table such as Python's dict that finds any key in average O(1) time) with a doubly linked list (a chain of nodes where every node stores prev and next pointers to both of its neighbors), capped at both ends by two sentinel nodes (permanent dummy head and tail placeholder nodes that store no real data so every real node always has two valid neighbors).
Why do simpler single-structure designs fall short? Keeping entries in a plain Python list or collections.deque preserves recency order, yet finding or removing a key from the middle shifts neighboring items and costs O(capacity) time per call. Storing key -> (value, last_used_timestamp) in a plain dictionary makes reads and updates O(1), yet finding the smallest timestamp when evicting still requires scanning the whole dictionary in O(capacity) time (or O(log n) with a heap). By pointing each dictionary entry directly at its doubly linked list node, we jump to any node in average O(1) time and splice it out or move it to the front in worst-case O(1) pointer updates.
Here is Example 1 (capacity = 2) traced step by step:
1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [20:200] <-> [10:100] <-> tail
3. get(10) -> returns 100, promotes 10 to front:
head <-> [10:100] <-> [20:200] <-> tail
4. put(30, 300) -> full (size 2 == capacity 2), evicts tail.prev ([20:200]):
head <-> [30:300] <-> [10:100] <-> tail
5. get(20) -> key 20 is no longer in self.nodes -> returns -1
6. get(10) -> returns 100, promotes 10 to front
Complexity
Let m be the number of operations and c be max(0, capacity).
- Time: average
O(1)pergetandput, andO(m)total across the run. Eachgetorputperforms at most two dictionary operations (in, lookup, insert, ordel, each averageO(1)) plus a constant number of pointer assignments in_unlinkand_push_front(worst-caseO(1)), never scanning the list. - Space:
O(min(c, m))for the cache (O(c)upper bound), plusO(m)for the judge's output list. The cache holds at mostcrealNodeobjects,cdictionary entries inself.nodes, and two fixed sentinel nodes (headandtail).
Edge cases
- Zero or negative capacity (
capacity <= 0):putreturns immediately without storing anything, and everygetreturns-1(Example 3). - Capacity
1: Every new key evicts the single stored key, whereas overwriting that same key updates its value without evicting anything. - Overwriting an existing key when full:
putupdates the value in place and moves the node tohead.nextwithout evictingtail.prev(Example 2). - Cache miss on
get: Returns-1, does not insert the missing key, and leaves the recency order of existing keys untouched. - Zero values and negative keys: Stored values such as
0and negative integer keys work normally because misses are checked viakey not in self.nodes, not truthiness. - Empty operation list: Returns
[]cleanly.
Common mistakes
- Forgetting to promote on
get: Treatinggetas a read-only lookup turns the cache into First-In-First-Out (FIFO) instead of LRU, evicting hot keys that were inserted early. - Evicting before checking
key in self.nodesinput: Iflen(self.nodes) == self.capacityruns beforeif key in self.nodes, updating an existing key in a full cache wrongly deletes an innocent entry. - Omitting
self.keyonNode: Whenputevictstail.prev, it has theNodeobject in hand, yet withoutlru_node.keyit cannot delete the corresponding entry fromself.nodesinO(1)time. - Skipping the
capacity <= 0guard: On an empty cache withcapacity == 0,len(self.nodes) == self.capacityevaluates to0 == 0, causingself.tail.prevto unlinkself.headand corrupt the sentinels. - Using
listorcollections.dequefor recency order: Removing an element from the middle of either structure takesO(c)time, quietly degradinggetandputfromO(1)to linear time.
Alternative approaches
- Python's
collections.OrderedDict:OrderedDictalready pairs a hash table with a doubly linked list in C. Callingmove_to_end(key)marks a key as most recent inO(1)andpopitem(last=False)evicts the oldest key inO(1). Mention it as the idiomatic production choice in Python, then buildNode+dictmanually because interviewers ask this problem specifically to see pointer design. - Timestamps with a min-heap: Store a monotonically increasing counter on every access and push
(timestamp, key)onto a min-heap (a binary tree stored in an array whose smallest element sits at index0and pops inO(log n)time), using lazy deletion (leaving outdated(timestamp, key)pairs in the heap and discarding them when they surface during eviction). This is slower (O(log n)per operation) and uses extra memory for stale heap entries until rebuilt.
Follow-up questions
- How would you synchronize this cache for multi-threaded reads and writes without creating a single global bottleneck? Because
getmutates pointers inside the doubly linked list to promote hits, concurrent reads still mutate shared state, so a reader-writer lock provides no advantage over a standard mutex (a mutual-exclusion lock such asthreading.Lockallowing one thread insidegetorputat a time). When a single lock becomes hot under heavy concurrency, use sharding (splitting keys acrossSindependent sub-caches of capacityc / Sselected byhash(key) % S, each guarded by its own lock), trading exact global LRU eviction for near-zero lock contention. - How can you extend each entry with a time-to-live (TTL) expiration window while keeping operations fast? Save an
expires_atdeadline on eachNodewhen written. Onget(key), checknow >= node.expires_at; if expired, unlink the node, deleteself.nodes[key], and return-1— known as lazy expiry (reclaiming expired entries when touched rather than scheduling per-key timers). To prevent cold expired keys from occupying space forever, combine lazy expiry with either a lightweight background sweep or a secondary queue/min-heap ordered byexpires_at. - What API change is needed if callers must be able to cache -1 as an ordinary integer value? Using
-1as the miss sentinel makes a miss indistinguishable from a hit whose cached payload happens to be-1. Widen the return contract ofgetto returnOptional[int](Noneon a miss), return a(found: bool, value: Optional[int])pair, or raiseKeyErroron misses like Python'sdict.
Follow-up questions
- How would you synchronize this cache for multi-threaded reads and writes without creating a single global bottleneck?
- How can you extend each entry with a time-to-live (TTL) expiration window while keeping operations fast?
- What API change is needed if callers must be able to cache -1 as an ordinary integer value?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array