Least Recently Used (LRU) Cache
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a bounded Least Recently Used (LRU) key-value cache initialized with a positive integer capacity, evaluated through the driver function lru_cache_operations(capacity, operations, arguments).
The cache supports two operations, both running in O(1) average time:
get(key) -> int: Searches forkey. On a hit, markskeyas the most recently accessed entry and returns its associated value. On a miss, leaves recency order unchanged and returns-1.put(key, value) -> None: Writes(key, value)and markskeyas the most recently accessed entry. Ifkeyis already stored, its value is overwritten in place without evicting any entry. Ifkeyis absent and the cache already holdscapacityentries, first evict whichever stored key has gone the longest without agethit orputwrite.
Given capacity, a list operations of "put" and "get" strings, and a matching list arguments ([key, value] for "put", [key] for "get"), lru_cache_operations initializes one cache and returns a list recording None for each "put" and the integer result for each "get".
Examples
Example 1
- Input:
capacity = 2operations = ["put", "put", "get", "put", "get", "get"]arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [30]]
- Output:
[None, None, 100, None, -1, 300] - Explanation: After inserting
10: 100and20: 200, callingget(10)returns100and promotes key10ahead of key20. Inserting30: 300into the full cache therefore evicts key20, soget(20)returns-1whileget(30)returns300.
Example 2
- Input:
capacity = 2operations = ["put", "put", "put", "get", "put", "get", "get"]arguments = [[4, 40], [7, 70], [4, 45], [9], [8, 80], [7], [4]]
- Output:
[None, None, None, -1, None, -1, 45] - Explanation:
put(4, 45)updates existing key4to45and refreshes its recency without evicting key7. The missedget(9)returns-1and does not disturb recency, soput(8, 80)evicts key7, leaving keys8and4(45).
Constraints
1 <= capacity <= 1000key >= 0andvalue >= 0(non-negative integers)0 <= len(operations) == len(arguments) <= 2 * 10^5- Both
getandputmust run inO(1)average time
Step-by-step walkthrough
Restate the problem and the eviction rules
We want to build a Least Recently Used (LRU) cache of positive size
capacitysupporting two operations inO(1)average time:get(key) -> int: Ifkeyis in the cache, mark it as most recently used and return its value; otherwise return-1without changing anything.put(key, value) -> None:- If
keyis already in the cache, update its value and mark it as most recently used (never evicting anything!). - If
keyis new and the cache is already atcapacity, first evict the least recently used key, then insert(key, value)as the most recently used item.
- If
The judge tests our class through
lru_cache_operations(capacity, operations, arguments), returningNonefor each"put"and the integer answer for each"get".Why a list or a dictionary alone cannot hit O(1)
Suppose we kept entries in a plain Python
listordered from least to most recently used. Evicting the oldest item (pop(0)) or finding a key to move it to the back requires scanning and shifting up tocapacityelements—O(capacity)per call instead ofO(1).On the other hand, a plain dictionary gives
O(1)key lookup, but a raw hash table gives noO(1)way to pull an arbitrary middle item out of a recency chain and splice it onto the front.To get
O(1)for both lookup and reordering, we combine two data structures so each covers the other's weakness: - A dictionarynodes(key -> Node): jumps directly to any key's node inO(1)average time. - A doubly linked list ofNodeobjects: keeps nodes ordered from Most Recently Used (MRU) at the front to Least Recently Used (LRU) at the back, letting us detach any node and re-attach it at the front inO(1)pointer updates.Visual blueprint: sentinel nodes and why each node stores its key
Here is how
nodesand the doubly linked list work together:Dictionary `nodes`: key 10 -------------------> +------------+ key 20 ----+ | key = 10 | (LRU: oldest, next to be evicted) | | val = 100 | v +------------+ +------------+ ^ | key = 20 | (MRU) | | val = 200 | v +------+ +------------+ +------------+ +------+ | head |<->| key=20,200 |<----->| key=10,100 |<->| tail | +------+ +------------+ +------------+ +------+ (dummy) (head.next) (dummy) newest (tail.prev) oldestThree small design choices keep the code clean and bug-free:
- Why doubly linked (
prevandnext)? Whenget(10)hits a node in the middle of the chain, we must stitch its left neighbor directly to its right neighbor. Storingnode.prevgives us the left neighbor immediately inO(1)instead of walking fromheadinO(n). - Why store
keyinsideNode? When the cache is full, we find the eviction victim from the list (oldest = self.tail.prev), and we must also delete its entry fromself.nodesviadel self.nodes[oldest.key]. - Why permanent
headandtaildummy sentinels? Initiallyhead <-> tail. Becauseheadandtailare never removed, every real node always sits strictly between two non-Nonenodes—so we never needif node.prev is Noneorif self.head is Nonebranches!
- Why doubly linked (
Code Node and the two pointer-rewiring helpers
Every recency change boils down to two tiny
O(1)pointer operations—_unlink(node)and_push_front(node):_unlink(node): bypass `node` by connecting `prev_node` <-> `next_node` Before: [prev_node] <-> [node] <-> [next_node] After: [prev_node] <------------> [next_node] _push_front(node): splice `node` right between `head` and `first = head.next` Before: [head] <-----------------> [first] After: [head] <-> [node] <------> [first]Saving
prev_node,next_node, andfirst = self.head.nextin local variables makes the pointer updates effortless to read and impossible to scramble:from typing import Dict, Optional class Node: def __init__(self, key: int, value: int): # Store `key` alongside `value` so when we evict `tail.prev`, we know 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 # nodes: maps cached key -> its Node in the doubly linked list, e.g. {10: Node(10, 100)}. self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes permanently frame the list: head <-> [MRU ... LRU] <-> tail. # Real nodes always have non-None `prev` and `next`, avoiding empty/boundary special cases. 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: # Phase: Detach `node` from its current spot by wiring its neighbors directly to each other. 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: # Phase: Insert `node` right after `head` so `head.next` is always the most recently used item. first = self.head.next assert first is not None self.head.next = node node.prev = self.head node.next = first first.prev = nodeCode get, put, and the operation runner
Watch two classic traps in
getandput: - Testif node is None:, neverif not node:or truthiness onvalue—becausekey = 0andvalue = 0are completely valid cached numbers! - Input, handle an existing key before checkinglen(self.nodes) == self.capacity: updating an already-cached key when the cache is full replaces its value in place and must not evict another key.def get(self, key: int) -> int: node = self.nodes.get(key) # Check `is None` explicitly because 0 is a valid cached value. if node is None: return -1 # A cache hit counts as a fresh use: move `node` to the front (MRU position). self._unlink(node) self._push_front(node) return node.value def put(self, key: int, value: int) -> None: node = self.nodes.get(key) if node is not None: # Phase 1 (update): Key is already cached -> update value, move to MRU, and NEVER evict. node.value = value self._unlink(node) self._push_front(node) return # Phase 2 (evict if full): Only a brand-new key on a full cache triggers eviction of `tail.prev` (LRU). if len(self.nodes) == self.capacity: oldest = self.tail.prev assert oldest is not None self._unlink(oldest) del self.nodes[oldest.key] # Phase 3 (insert): Create the new node, index it in the map, and place it at MRU. new_node = Node(key, value) self.nodes[key] = new_node self._push_front(new_node)Finally,
lru_cache_operationsinitializes oneLRUCache(capacity)and replays the sequence of"put"and"get"calls:from typing import List, Optional def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: # Judge harness: initialize one LRUCache and replay all get/put operations. cache = LRUCache(capacity) results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "put": cache.put(args[0], args[1]) results.append(None) elif op == "get": results.append(cache.get(args[0])) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 1 pointer-by-pointer
Let's trace Example 1 (
capacity = 2):Start: nodes = {} head <-> tail -> - put(10, 100): nodes = {10} head <-> [10:100] <-> tail -> None put(20, 200): nodes = {10, 20} head <-> [20:200] <-> [10:100] <-> tail -> None get(10): hit! move [10:100] MRU head <-> [10:100] <-> [20:200] <-> tail -> 100 put(30, 300): full! evict tail.prev ([20:200]), delete key 20, push [30:300]: nodes = {10, 30} head <-> [30:300] <-> [10:100] <-> tail -> None get(20): key 20 not in `nodes` head <-> [30:300] <-> [10:100] <-> tail -> -1 get(30): hit! [30:300] at MRU head <-> [30:300] <-> [10:100] <-> tail -> 300Returned list:
[None, None, 100, None, -1, 300].Complete 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`, we know 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 # nodes: maps cached key -> its Node in the doubly linked list, e.g. {10: Node(10, 100)}. self.nodes: Dict[int, Node] = {} # Dummy sentinel nodes permanently frame the list: head <-> [MRU ... LRU] <-> tail. # Real nodes always have non-None `prev` and `next`, avoiding empty/boundary special cases. 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: # Phase: Detach `node` from its current spot by wiring its neighbors directly to each other. 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: # Phase: Insert `node` right after `head` so `head.next` is always the most recently used item. first = self.head.next assert first is not None self.head.next = node node.prev = self.head node.next = first first.prev = node def get(self, key: int) -> int: node = self.nodes.get(key) # Check `is None` explicitly because 0 is a valid cached value. if node is None: return -1 # A cache hit counts as a fresh use: move `node` to the front (MRU position). self._unlink(node) self._push_front(node) return node.value def put(self, key: int, value: int) -> None: node = self.nodes.get(key) if node is not None: # Phase 1 (update): Key is already cached -> update value, move to MRU, and NEVER evict. node.value = value self._unlink(node) self._push_front(node) return # Phase 2 (evict if full): Only a brand-new key on a full cache triggers eviction of `tail.prev` (LRU). if len(self.nodes) == self.capacity: oldest = self.tail.prev assert oldest is not None self._unlink(oldest) del self.nodes[oldest.key] # Phase 3 (insert): Create the new node, index it in the map, and place it at MRU. new_node = Node(key, value) self.nodes[key] = new_node self._push_front(new_node) def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: # Judge harness: initialize one LRUCache and replay all get/put operations. cache = LRUCache(capacity) results: List[Optional[int]] = [] for op, args in zip(operations, arguments): if op == "put": cache.put(args[0], args[1]) results.append(None) elif op == "get": results.append(cache.get(args[0])) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
A Least Recently Used (LRU) cache works like a small stack of folders on your desk: whenever you read a folder (get) or update/add one (put), you place that folder right on top; when your desk runs out of room, you file away whichever folder has sunk all the way to the bottom because you haven't touched it in the longest time. To make both looking up any folder by name and moving it to the top take O(1) constant time, we pair a hash map (a key-value dictionary that jumps directly to any key in O(1) average time) with a doubly linked list (a chain of nodes where every node stores prev and next pointers to both neighbors, allowing O(1) removal from the middle and insertion at the front). Framing the list with two permanent sentinel nodes (head and tail dummy placeholders that are never evicted) ensures every real node always has two real neighbors, eliminating null-pointer edge cases.
Using either structure on its own falls short. Storing (key, value) pairs in a plain array or list makes finding a key or shifting items after removal take O(capacity) linear time per call. Conversely, a standalone hash table finds keys in O(1) time, but without doubly linked prev and next pointers there is no O(1) way to splice a freshly accessed key out of the middle of the recency order or jump straight to the oldest item on eviction.
Let's walk through Example 1 (capacity = 2):
- put(10, 100) then put(20, 200): the list from newest to oldest is head <-> [20:200] <-> [10:100] <-> tail.
- get(10): nodes[10] jumps straight to [10:100] in O(1), unlinks it, and pushes it after head, reordering the list to head <-> [10:100] <-> [20:200] <-> tail and returning 100.
- put(30, 300): key 30 is new and len(nodes) == 2 == capacity, so we evict tail.prev ([20:200]), delete key 20 from nodes, and push [30:300] at the front: head <-> [30:300] <-> [10:100] <-> tail.
- get(20) and get(30): key 20 is no longer in nodes (-1), while key 30 hits and returns 300.
Complexity
- Time:
O(1)average pergetandput(O(n)total to replaynoperations). Each call performs at most twoO(1)average dictionary operations (get, assignment, ordel) and rewires a fixed number (four) of linked-list pointers with zero loops. - Space:
O(capacity), because the dictionary and doubly linked list store at mostcapacityNodeobjects at any moment (plus the two fixedheadandtailsentinels).
Edge cases
- Empty cache (
getbefore anyput):self.nodes.get(key)returnsNoneandgetimmediately returns-1;head.nextsafely points totail. - Capacity of
1:head.nextandtail.prevpoint to the single cached node, and every new key cleanly evicts it before inserting. - Updating an existing key when full:
putchecksif node is not None:before checkinglen(self.nodes) == self.capacity, so updating an existing key never evicts another entry. - Updating an existing key refreshes its recency:
put(4, 45)in Example 2 moves key4tohead.next, making key7the next eviction victim. - Missed
getleaves recency untouched: querying a missing key returns-1without modifying any pointers. - Zero keys and zero values (
put(0, 0)): testingif node is None:avoids treating0as falsy/missing.
Common mistakes
- Evicting before checking whether
keyalready exists: if a full cache evicts first onput(existing_key, new_val), it wrongly drops a valid key and shrinks below capacity. - Forgetting to move the node to the front on
getor onputupdates: without refreshing recency on hits and updates, the cache turns into FIFO (First-In, First-Out) instead of LRU. - Forgetting
del self.nodes[oldest.key]during eviction (or omittingkeyfromNode): unlinkingtail.prevfrom the list without deleting its dictionary entry causes stale hits and unbounded memory growth. - Using a singly linked list: without
node.prev, unlinking a middle node requires walking fromheadinO(capacity)time.
Alternative approaches
collections.OrderedDict: Python's standard-libraryOrderedDictimplements this exact hash-map-plus-doubly-linked-list pattern in C viamove_to_end(key)andpopitem(last=False)inO(1)time. In an interview, mentionOrderedDictas the production Python choice and then write the explicitNodeimplementation to demonstrate how it works under the hood.- Plain Python 3.7+
dictdeletion + re-insertion: deleting and re-inserting a key moves it to the end whilenext(iter(d))finds the oldest key, but repeated front deletions leave dead dummy slots at the start of CPython's internal entry table until a resize occurs, degradingnext(iter(d))away from steadyO(1)on large caches.
Follow-up questions
- How can you adapt this cache so multiple threads can call get and put safely without killing throughput? Because even
get(key)mutatesprevandnextpointers to move the hit node to the front, a reader-writer lock does not allow concurrent reads—every hit is a write. The cleanest correct baseline wrapsgetandputin a single mutex (lock) (threading.Lock, ensuring only one thread modifies the map and list at a time). Under heavy multi-core contention, split the cache intoSindependent LRU shards indexed byhash(key) % S, each with capacitycapacity / Sand its own lock, or buffer read-hit recency updates in thread-local queues and apply them in batches to approximate LRU with near-lock-free reads. - How would you redesign the data structures to evict the Least Frequently Used (LFU) key in O(1) time instead? Least Frequently Used (LFU) evicts the key with the lowest access count, breaking ties by least recent use. To keep both
getandputinO(1)time, storenodes: key -> Node(key, value, freq), a second mapfreq_lists: freq -> doubly linked list(each list ordered from MRU to LRU), and an integermin_freq. Whenever a key with frequencyfis accessed, unlink it fromfreq_lists[f], incrementmin_freqtof + 1iffreq_lists[f]became empty andf == min_freq, and push the node to the front offreq_lists[f + 1]; on eviction, poptail.prevfromfreq_lists[min_freq](and resetmin_freq = 1when inserting a brand-new key). - When scaling to millions of cached keys, how can you reduce the per-entry memory overhead of doubly linked nodes? Every cached item allocates both a hash-table slot and a
Nodeobject carrying two 8-byte pointers (prev,next) plus object header metadata—in Python, adding__slots__ = ("key", "value", "prev", "next")eliminates each node's per-instance__dict__and cuts node memory substantially, while in C++/Rust preallocating flat integer arraysprev[capacity]andnext[capacity]replaces 8-byte pointers with 4-byte slot indices and improves CPU cache locality. If exact LRU ordering is not strictly required, the CLOCK (second-chance) algorithm (a circular buffer with a single 1-bit "recently used" flag per entry instead of two pointers) slashes metadata overhead to almost nothing. Finally, when cached values vary widely in byte size, cap total memory bytes rather than entry count so a handful of multi-megabyte values cannot trigger an out-of-memory crash.
Follow-up questions
- How can you adapt this cache so multiple threads can call get and put safely without killing throughput?
- How would you redesign the data structures to evict the Least Frequently Used (LFU) key in O(1) time instead?
- When scaling to millions of cached keys, how can you reduce the per-entry memory overhead of doubly linked nodes?
Similar questions
- Surviving Robot Score After Pairwise Clashes
- Reconstruct Binary Tree from Inorder and Postorder Traversals
- Relayable Server Pairs Across a Weighted Tree
- Counting Repeat-Free Contiguous Substrings
- Production HTTP API Design for Vision Model Serving
- Lattice Point Reachability Under Coordinate Sums
- LFU Cache Command Processor
More NVIDIA interview questions
- Off-Hours Learning, Role Scope, and Technical Project Walkthrough Medium
- Modern ML Framework Evolution: PyTorch vs. JAX Medium
- Same 4 KB Memory Page Easy Pro
- Range Count of Ideal Integers Easy Pro
- Exact Fixed-Iteration K-Means Clustering Hard Pro
- Balanced Bracket Sequence Easy Pro
- Multi-Resolution Fleet GPU Telemetry and Drilldown System Hard Pro
- Sliding-Window Top-K Event Stream Tracker Medium Pro
- Java vs. Python: Runtime Architecture, Type Systems, and Workload Fit Medium Pro
- Surviving Robot Score After Pairwise Clashes Easy Pro