In-Memory Cache With LRU Eviction
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a fixed-size key-value cache driven by lru_cache(capacity, operations, arguments) that evicts its least recently accessed entry whenever a new key must fit into a full store.
The cache starts empty with maximum slot count capacity and processes commands from parallel lists operations and arguments:
"get"witharguments[i] = [key]: Look upkey. Whenkeyis currently cached, promote that entry to become the most recently accessed item and output its stored integer value. Whenkeyis absent, output-1and leave the existing recency order unchanged."put"witharguments[i] = [key, value]: Associatekeywithvalue, promotekeyto become the most recently accessed item, and appendNoneto the output list. Overwriting a key that is already cached updates its value in place without evicting any entry. Inserting a brand-new key when the cache already holdscapacitykeys first removes whichever cached key has gone the longest without a"get"hit or"put"write.
Return a list containing one result (int or None) per command in operations. Every "get" and "put" call must execute in O(1) amortized time.
Examples
Example 1
- Input:
capacity = 2operations = ["put", "put", "get", "put", "get", "put", "put", "get", "get", "get"]arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [10, 150], [40, 400], [30], [10], [40]]
- Output:
[None, None, 100, None, -1, None, None, -1, 150, 400] - Explanation:
put(10, 100)andput(20, 200)fill both slots (20is newest,10is oldest).get(10)returns100and promotes key10, making key20the oldest entry.put(30, 300)needs space for a new key, so it evicts20and caches30 -> 300.get(20)misses and returns-1.put(10, 150)updates key10in place without evicting30, promoting10ahead of30.put(40, 400)evicts the oldest key30and caches40 -> 400.- Subsequent lookups return
-1for30,150for10, and400for40.
Example 2
- Input:
capacity = 1operations = ["get", "put", "get", "put", "get", "get"]arguments = [[5], [5, 50], [5], [8, 80], [5], [8]]
- Output:
[-1, None, 50, None, -1, 80] - Explanation: Reading key
5on an empty cache returns-1. After storing5 -> 50and reading50, inserting8 -> 80into the single-slot cache evicts key5, soget(5)returns-1whileget(8)returns80.
Constraints
1 <= capacity <= 3,0000 <= len(operations) == len(arguments) <= 100,000- Each
operations[i]is either"get"(witharguments[i] = [key]) or"put"(witharguments[i] = [key, value]). -10^5 <= key, value <= 10^5- Both
"get"and"put"must run inO(1)amortized time.
Step-by-step walkthrough
Understand the goal and the judge format
We need to build an in-memory key-value cache with a fixed positive
capacityand a least-recently-used (LRU) eviction rule:get(key)looks upkey. If it is missing, return-1and leave the cache untouched. If it is present, return its value and markkeyas the most recently used entry.put(key, value)storesvalueunderkey. Ifkeyis already in the cache, overwrite its value and markkeyas most recently used (no eviction happens because the number of stored keys did not grow). Ifkeyis brand-new and the cache already holdscapacityitems, first evict the least recently used entry — the one that has gone the longest without agetorput— and then insert the new entry as most recently used.
Both
getandputmust run in amortized O(1) time (constant average work per call).The judge tests our class through
lru_cache(capacity, operations, arguments): it creates one cache of sizecapacity, runs eachoperations[i]witharguments[i]([key]for"get",[key, value]for"put"), and collects one output per operation (the integer result for"get", orNonefor"put").Why one data structure alone is too slow
To make both operations O(1), we need to do three things in constant time:
- Find an entry by
key. - Move any existing entry to the "most recently used" front when it is read or updated.
- Drop the "least recently used" entry from the back when a full cache needs room.
Neither a list nor a plain dictionary can do all three alone:
- A plain list of
[key, value]pairs keeps entries in order, so the oldest entry sits at one end. However, finding a key requires scanning the list, and removing an entry from the middle shifts every element after it — costingO(capacity)time per call. - A plain hash map (
dict) finds any key inO(1)average time, but without linked pointers between entries you cannot pull an arbitrary middle item out and move it to the front inO(1)time using basic dictionary lookups alone.
The solution is to pair both structures together: a dictionary
key_to_nodemaps eachkeydirectly to itsNodeinside a doubly linked list ordered from most recently used to least recently used.- Find an entry by
Combine a dictionary with a doubly linked list and dummy sentinels
Here is how the dictionary and the doubly linked list work together right after
put(30, 300)in Example 1 (capacity = 2):key_to_node (dict) Doubly linked recency list ------------------ -------------------------- [head] (dummy sentinel, never evicted) ⇅ 30 ───────────────────► [30 : 300] (most recently used = head.next) ⇅ 10 ───────────────────► [10 : 100] (least recently used = tail.prev) ⇅ [tail] (dummy sentinel, never evicted)Three small design choices eliminate edge-case bugs:
- Doubly linked (
prevandnextpointers): Whenkey_to_node[key]hands us a node in the middle of the list, we need bothnode.prevandnode.nextto stitch its neighbors together in O(1). A singly linked list would force anO(capacity)search from the head just to findnode.prev. - Each
Nodestores bothkeyandvalue: When the cache is full, we find the victim from the list (tail.prev), and we also need to delete that victim fromkey_to_node. Storingkeyon the node tells us which dictionary key to delete. - Dummy sentinel
headandtailnodes: Even when the cache holds zero items (head <-> tail), every real node we ever insert or remove sits strictly betweenheadandtail. That guaranteesnode.prevandnode.nextare neverNone, so we never needifbranches for an empty list or capacity 1.
class Node: """One cache entry stored inside the doubly linked recency list.""" def __init__(self, key: int, value: int): # Store key alongside value so evicting tail.prev knows 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: dict mapping int key -> Node currently inside the doubly linked list self.key_to_node: Dict[int, Node] = {} # Dummy sentinel nodes keep the list framed as: # head <-> [most recent] <-> ... <-> [least recent] <-> tail # Because head and tail are never removed, real nodes always have non-None neighbors. self.head = Node(0, 0) self.tail = Node(0, 0) self.head.next = self.tail self.tail.prev = self.head- Doubly linked (
Write the three O(1) list pointer helpers
Every change to recency order reduces to two tiny pointer operations:
_unlink(node)detachesnodefrom wherever it currently sits by connectingprev_nodeandnext_nodedirectly to each other._push_front(node)splicesnoderight betweenself.headandold_first = self.head.next. Savingold_firstin a local variable first makes the four pointer assignments impossible to mix up:
Before _push_front(node): head <──────────────> old_first After _push_front(node): head <──> node <──> old_firstMarking an existing node as most recently used (
_move_to_front) simply calls_unlink(node)followed by_push_front(node).def _unlink(self, node: Node) -> None: # Bypass node by wiring its left and right neighbors directly to each other in O(1). prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: Node) -> None: # Insert node right after dummy head (the most-recently-used position). old_first = self.head.next node.prev = self.head node.next = old_first old_first.prev = node self.head.next = node def _move_to_front(self, node: Node) -> None: # Refreshing an entry's recency = detach from current spot + insert at front. self._unlink(node) self._push_front(node)Implement get and put without eviction traps
Now
getandputread like plain English, provided we watch out for two classic traps:- In
get(key), testif node is None:(neverif not node.value:). A cached value of0(or even-1) is still a valid cache hit that must refresh recency and return the stored number. - In
put(key, value), check whetherkeyalready exists BEFORE checking capacity. Updating an existing key in a full cache keeps the entry count unchanged. If you checkedlen(self.key_to_node) == self.capacityfirst, updating an existing key in a full cache would mistakenly evict another key!
def get(self, key: int) -> int: node = self.key_to_node.get(key) # Test `is None` explicitly so cached values like 0 or -1 still count as hits. 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.key_to_node.get(key) if existing_node is not None: # Updating an existing key never increases cache size, so nothing is evicted. existing_node.value = value self._move_to_front(existing_node) return if len(self.key_to_node) == self.capacity: # Cache is full and key is new: evict the least-recently-used node right before tail. lru_node = self.tail.prev self._unlink(lru_node) del self.key_to_node[lru_node.key] # Insert the brand-new entry into both the hash map and the front of the list. new_node = Node(key, value) self.key_to_node[key] = new_node self._push_front(new_node)- In
Replay the operations and trace Example 1
Finally,
lru_cacheinstantiatesLRUCache(capacity)and loops through(op, args)pairs:def lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: cache = LRUCache(capacity) # results: one output per call (int value 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("unknown operation: " + op) return resultsLet's trace Example 1 (
capacity = 2) from start to finish, showing the list fromhead(MRU) totail(LRU) after each call:Call Output List state (head <-> MRU ... LRU <-> tail) ------------- ------ ------------------------------------------------ put(10, 100) None head <-> [10:100] <-> tail put(20, 200) None head <-> [20:200] <-> [10:100] <-> tail get(10) 100 head <-> [10:100] <-> [20:200] <-> tail (10 moves to front!) put(30, 300) None head <-> [30:300] <-> [10:100] <-> tail (full: tail.prev [20:200] evicted) get(20) -1 head <-> [30:300] <-> [10:100] <-> tail (miss: list unchanged) put(10, 150) None head <-> [10:150] <-> [30:300] <-> tail (update in place + move to front) put(40, 400) None head <-> [40:400] <-> [10:150] <-> tail (full: tail.prev [30:300] evicted) get(30) -1 head <-> [40:400] <-> [10:150] <-> tail (miss: list unchanged) get(10) 150 head <-> [10:150] <-> [40:400] <-> tail (10 moves to front) get(40) 400 head <-> [40:400] <-> [10:150] <-> tail (40 moves to front)Collecting the outputs gives
[None, None, 100, None, -1, None, None, -1, 150, 400]. Notice how bothget(10)andput(10, 150)rescued key10by moving it ahead of the other cached key, causing20and then30to be evicted instead.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class Node: """One cache entry stored inside the doubly linked recency list.""" def __init__(self, key: int, value: int): # Store key alongside value so evicting tail.prev knows 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: dict mapping int key -> Node currently inside the doubly linked list self.key_to_node: Dict[int, Node] = {} # Dummy sentinel nodes keep the list framed as: # head <-> [most recent] <-> ... <-> [least recent] <-> tail # Because head and tail are never removed, real nodes always have non-None neighbors. 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: # Bypass node by wiring its left and right neighbors directly to each other in O(1). prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _push_front(self, node: Node) -> None: # Insert node right after dummy head (the most-recently-used position). old_first = self.head.next node.prev = self.head node.next = old_first old_first.prev = node self.head.next = node def _move_to_front(self, node: Node) -> None: # Refreshing an entry's recency = detach from current spot + insert at front. self._unlink(node) self._push_front(node) def get(self, key: int) -> int: node = self.key_to_node.get(key) # Test `is None` explicitly so cached values like 0 or -1 still count as hits. 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.key_to_node.get(key) if existing_node is not None: # Updating an existing key never increases cache size, so nothing is evicted. existing_node.value = value self._move_to_front(existing_node) return if len(self.key_to_node) == self.capacity: # Cache is full and key is new: evict the least-recently-used node right before tail. lru_node = self.tail.prev self._unlink(lru_node) del self.key_to_node[lru_node.key] # Insert the brand-new entry into both the hash map and the front of the list. new_node = Node(key, value) self.key_to_node[key] = new_node self._push_front(new_node) def lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: cache = LRUCache(capacity) # results: one output per call (int value 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("unknown operation: " + op) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a narrow shelf on your desk that holds at most capacity reference books, paired with a card catalog right next to it. Whenever you look up a book (get) or place a book on the shelf (put), you slide that book into the leftmost spot so the books you touched most recently always sit near the left end. When the shelf is completely full and a brand-new book arrives, the book sitting at the rightmost end — the least recently used (LRU) one, meaning the item that has gone the longest without being read or updated — is pushed off the shelf to make room.
Why can't we use just a Python list or just a plain dictionary? A plain list keeps items in order, but finding a key or pulling an item out of the middle shifts all later elements and takes O(capacity) time per call. A plain hash map (dict, a key-value table that jumps straight to a key's bucket using its hash code) finds keys in O(1) average time, but gives you no way to pull an arbitrary middle item to the front in O(1) without linked pointers. By combining a dictionary (key -> Node) with a doubly linked list (a chain of nodes where each node points to both its left neighbor prev and right neighbor next), the dictionary jumps straight to any node in O(1) and the list rewires four neighbor pointers in O(1). We also cap the ends of the list with two sentinel nodes (permanent dummy head and tail nodes that hold no real data) so we never have to write special None checks for an empty cache or single-element edge cases.
Here is a tiny trace with capacity = 2 on the first five calls of Example 1 (put(10, 100), put(20, 200), get(10), put(30, 300), get(20)):
1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [20:200] <-> [10:100] <-> tail (20 is MRU, 10 is LRU)
3. get(10)->100 -> head <-> [10:100] <-> [20:200] <-> tail (reading 10 moves it to MRU!)
4. put(30, 300) -> full! evict tail.prev ([20:200]), delete key 20 from dict,
insert [30:300] at front -> head <-> [30:300] <-> [10:100] <-> tail
5. get(20)-> -1 -> key 20 is no longer in dict -> cache miss (-1)
Complexity
Let C be capacity and M be the number of operations replayed by lru_cache.
- Time:
O(1)amortized pergetandput(O(M)total acrossMoperations). AmortizedO(1)means that even though the underlying hash table occasionally resizes and copies its buckets, the total cost averaged over any sequence of operations is a constant number of steps per call: one or twoO(1)dictionary lookups/updates plus at most six pointer assignments in_unlinkand_push_front. - Space:
O(C)for the cache (O(M)extra for the judge's output list). At any momentkey_to_nodeholds at mostCkeys and the doubly linked list holds at mostCrealNodeobjects plus the two permanent dummy sentinelsheadandtail.
Edge cases
capacity = 1: Every new key immediately evicts the sole cached key, whereas updating or reading that same key keeps it cached without error becauseheadandtailprevent neighbor pointers from ever becomingNone.- Updating an existing key when the cache is already full:
putupdates the value in place and moves the node to the front without evicting anything, because the total number of keys stays equal tocapacity. geton an empty cache or missing key: Returns-1immediately and leaves the recency order completely unchanged.- Cached value
0or negative numbers (including-1): Checkingif node is None:ensures a stored value of0returns0and refreshes recency. Note that with an API returning-1on misses, a caller cannot tell a stored-1apart from a miss externally, though internally our cache still tracks and refreshes that key properly. - Key
0: Even thoughself.headandself.tailare initialized asNode(0, 0), they are never inserted intoself.key_to_node, so user key0never collides with the sentinels.
Common mistakes
- Forgetting to move the node to the front on
get: A cache read counts as a recent use. Leaving the list untouched turns LRU into FIFO (first-in, first-out) and evicts recently read keys too early. - Checking capacity before checking whether
keyalready exists input: If the cache hascapacity = 2with{10: 100, 20: 200}andput(10, 150)runs, checking fullness first wrongly evicts key20even though10was only being updated. - Forgetting
del self.key_to_node[lru_node.key]on eviction: Unlinkingtail.prevfrom the linked list alone leaves a stale reference in the dictionary, allowinggetto keep returning evicted entries and letting memory grow without bound. - Overwriting
self.head.nexttoo early inside_push_front: If you writeself.head.next = nodebefore savingold_first = self.head.next, you lose your only pointer to the rest of the list and orphan every other cached entry. - Using a singly linked list or Python
list: Removing a node from the middle of a singly linked list requires walking fromheadto find its predecessor inO(C)time, andlist.pop(i)shifts elements inO(C)time.
Alternative approaches
- Python's
collections.OrderedDict:OrderedDictis implemented under the hood in C using this exact hash-table-plus-doubly-linked-list design. Callingmove_to_end(key)refreshes recency inO(1)andpopitem(last=False)evicts the oldest item inO(1). MentioningOrderedDictin an interview shows practical Python knowledge, and then buildingNode+LRUCacheby hand proves you understand the underlying data structure. - Plain list simulation (
O(C)per operation): Maintain[key, value]pairs in a list from oldest to newest. It is too slow for large capacities, but because its logic is tiny and obviously right, it makes an ideal brute-force oracle for randomized testing.
Follow-up questions
- How would you make this cache thread-safe under high concurrency without serializing every read behind a single global lock? A naive mutex (mutual-exclusion lock) around
getandputworks for low traffic, and a reader-writer lock (a lock allowing concurrent readers when no writer holds the lock) cannot parallelizegetbecause even cache reads mutate doubly linked list pointers to move the hit node to the front. To scale across many CPU cores, split the keyspace intoSindependent shards (separate mini-caches of capacityC / S, selected viahash(key) % S), each guarded by its own lock; threads touching different shards run in parallel while maintaining high-quality approximate LRU eviction. - How would you extend the design so each entry also expires automatically after a per-item time-to-live (TTL)? Store an
expires_attimestamp on eachNodeand first apply lazy expiration (checkingnow >= node.expires_atinsidegetandput, unlinking and deleting expired entries on sight inO(1)). Because unread expired nodes would otherwise occupy capacity until they drift totail, pair lazy checks either with periodic background sampling or with a min-heap (a priority queue ordered byexpires_atinO(log C)time) soputpurges expired entries before evicting live ones; if every entry shares an identical TTL duration, a FIFO queue (first-in, first-out queue) replaces the heap inO(1). - What changes if the capacity limit is measured in total bytes rather than number of keys, where values have variable byte sizes? Record
size_byteson eachNodeand maintain a runningused_bytessum on the cache. Reject (or bypass caching for) any single item withsize_bytes > capacity; otherwise updateused_byteson inserts and overwrites, then evictself.tail.previnside awhile used_bytes > capacity:loop. One largeputcan evict multiple small entries at once (O(C)worst-case for a single call), yet because every inserted node is evicted at most once over its lifetime,putstill runs in amortizedO(1)time.
Follow-up questions
- How would you make this cache thread-safe under high concurrency without serializing every read behind a single global lock?
- How would you extend the design so each entry also expires automatically after a per-item time-to-live (TTL)?
- What changes if the capacity limit is measured in total bytes rather than number of keys, where values have variable byte sizes?
Similar questions
- Valid Course Schedule Ordering
- Live Median Queries Over a Growing Integer Stream
- Smallest Value Meeting a Suffix Frequency Threshold
- Framing Length-Prefixed Packets from Async Byte Chunks
- Reconstruct Payload Strings from Tag-Linked Fragments
- Partition Words into Canonical Anagram Buckets
More Microsoft interview questions
- Peak Substring Frequency Under Character Bounds Medium
- Threshold-Sweep Precision-Recall Curve Easy
- Distinct Triplets Summing to Zero Medium Pro
- Longest Duplicate-Free Substring Length Medium Pro
- Consolidate Overlapping Intervals Medium Pro
- Minimum Highway Fuel Expense Medium Pro
- Smallest Daily Cargo Vessel Capacity Medium Pro
- Evaluating Binary Classifiers Under Unequal Error Costs Medium Pro
- Sequential Markdowns and Undiscounted Indices Hard Pro
- Worldwide Mobile 1-on-1 VoIP Calling Architecture Medium Pro