Bounded Key-Value Cache with Recency Eviction
Medium · Coding & Algorithms · Data Engineer · Technical Screen
Problem Statement
Simulate an initially empty in-memory cache that stores at most capacity distinct integer keys (capacity >= 1) and evicts its stalest entry whenever a new insertion exceeds that limit.
You are given capacity together with two equal-length lists, operations and arguments. Process each command operations[i] with parameter list arguments[i] in order and collect one output element per command:
"get"(arguments[i] = [key]): Ifkeyis currently stored, promotekeyto the most-recently-accessed position and append its stored integer value to the output list. Ifkeyis not stored, leave recency order unchanged and append-1."put"(arguments[i] = [key, value]): Ifkeyis already stored, replace its value withvalue, promotekeyto the most-recently-accessed position without evicting any key, and appendNone. Ifkeyis new, insert(key, value)at the most-recently-accessed position; if the cache now holds more thancapacitykeys, remove the key whose latest read hit or write happened furthest in the past, and appendNone.
In this variant, you do not need to build a doubly linked list—pairing a hash dictionary with a dynamic array/list whose key movements cost O(capacity) time is completely acceptable.
def run_lru_store(
capacity: int,
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
Examples
Example 1
Input:
capacity = 2
operations = ["put", "put", "get", "put", "get", "put", "get", "get"]
arguments = [[4, 400], [7, 700], [4], [9, 900], [7], [4, 450], [9], [4]]
Output:
[None, None, 400, None, -1, None, 900, 450]
Explanation: After put(4, 400) and put(7, 700), key 4 is oldest. Calling get(4) returns 400 and refreshes 4, leaving 7 as oldest. Inserting put(9, 900) exceeds capacity = 2 and evicts 7, so get(7) returns -1. Next, put(4, 450) overwrites key 4 in place without evicting 9, and the final reads return 900 and 450.
Example 2
Input:
capacity = 1
operations = ["get", "put", "get", "put", "get", "get"]
arguments = [[8], [8, 80], [8], [3, 30], [8], [3]]
Output:
[-1, None, 80, None, -1, 30]
Explanation: Reading 8 from an empty cache returns -1. After put(8, 80), get(8) returns 80. With capacity = 1, put(3, 30) immediately evicts 8, so get(8) returns -1 while get(3) returns 30.
Example 3
Input:
capacity = 2
operations = ["put", "put", "put", "put", "get", "get", "get"]
arguments = [[2, 12], [5, 50], [2, 25], [6, 60], [5], [2], [6]]
Output:
[None, None, None, None, -1, 25, 60]
Explanation: put(2, 12) and put(5, 50) fill both slots (2 oldest, 5 newest). Updating put(2, 25) promotes 2 to newest without evicting anything, so 5 becomes oldest and is evicted by put(6, 60).
Constraints
1 <= capacity <= 10000 <= len(operations) == len(arguments) <= 10^4- Each
operations[i]is"get"(with[key]) or"put"(with[key, value]). -10^9 <= key, value <= 10^9
Step-by-step walkthrough
Understand the input, output, and eviction rule
We need to simulate an in-memory cache holding at most
capacitydistinct keys (capacity >= 1). Whenever inserting a brand-new key pushes the key count abovecapacity, the cache performs eviction—removing the least recently used (LRU) key, meaning the entry that has gone untouched for the longest time.The harness passes
capacityalong with two parallel lists,operationsandarguments, and expects one result entry per command:"get"with[key]appends the stored integer value whenkeyis cached, or-1when it is absent."put"with[key, value]inserts or updateskeyand appendsNone.
capacity = 2 operations = ["put", "put", "get", "put", "get"] arguments = [[4, 400], [7, 700], [4], [9, 900], [7] ] results = [None, None, 400, None, -1 ]List every way recency can (and cannot) change
Most bugs in recency-eviction caches come from mixing up which events count as touching a key. Exactly four cases can happen:
get(key)whenkeyis cached (a cache hit): Return its value and promotekeyto the most-recently-used position.get(key)whenkeyis missing (a cache miss): Return-1and change nothing—missing keys are never added to recency order.put(key, value)whenkeyis already cached: Overwrite its value, promotekeyto the most-recently-used position, and evict nothing because the distinct key count did not grow.put(key, value)whenkeyis new: Insertkeyat the most-recently-used position. Only if the distinct key count now exceedscapacity, purge the single oldest key.
Pair a dictionary with a recency list
Each command requires two capabilities:
- Fast value lookup and update -> store
self.valuesas a dictionary mappingkey -> value. - Oldest-to-newest key tracking -> store
self.recency_orderas a list where index0(front) is the least recently used key and index-1(back) is the most recently used key.
recency_order: [ 7, 8, 4 ] ^ ^ index 0 index -1 oldest (evict!) newest (just used!) Touch key 8 --> remove 8, append 8 to back: recency_order: [ 7, 4, 8 ]We maintain one strict invariant (a property guaranteed to hold before and after every operation):
self.valuesandself.recency_orderalways hold the exact same set of keys. Moving an element in a Python list (remove+append, orpop(0)) shifts up tocapacityelements inO(capacity)time, which this problem explicitly permits.- Fast value lookup and update -> store
Implement initialization, recency refresh, and `get`
Centralizing the "remove and re-append to the back" step inside
_mark_most_recentensuresgethits andputupdates refresh keys identically. Notice thatgetchecksif key not in self.values:rather than testing value truthiness, because0is a valid cached integer!class LRUStore: """In-memory key-value store with least-recently-used (LRU) eviction.""" def __init__(self, capacity: int): self.capacity = capacity # values: dict mapping key -> stored value, e.g., {4: 400, 9: 900} self.values: Dict[int, int] = {} # recency_order: list of stored keys from oldest (index 0) to newest (index -1), e.g., [4, 9]. # Invariant: `values` and `recency_order` always contain the exact same set of keys. self.recency_order: List[int] = [] def _mark_most_recent(self, key: int) -> None: """Move an already-stored key to the newest end (back) of `recency_order`.""" self.recency_order.remove(key) self.recency_order.append(key) def get(self, key: int) -> int: # Check key membership with `in` (not value truthiness, since stored value 0 is valid). # A cache miss returns -1 and leaves `recency_order` completely unchanged. if key not in self.values: return -1 # A cache hit refreshes the key to most-recently-used before returning its value. self._mark_most_recent(key) return self.values[key]Implement `put`: separate updates from new insertions
Inside
put(key, value), check whetherkeyis already inself.valuesbefore touching capacity:- Existing key (update): Overwrite
self.values[key] = value, call_mark_most_recent(key), and return right away. Even when the cache is completely full, updating an existing key never evicts another key. - New key (insert + optional eviction): Add
keytoself.valuesand append it to the back ofself.recency_order. Iflen(self.values) > self.capacity, pop index0fromself.recency_orderand deleteoldest_keyfromself.values.
Example with capacity = 2, recency_order = [7, 4], values = {4: 400, 7: 700}: put(9, 900): 1. 9 is new -> append 9 to back: recency_order = [7, 4, 9] (3 keys > capacity 2) 2. pop(0) evicts oldest key 7: recency_order = [4, 9], delete 7 from valuesBecause
capacity >= 1and the newly inserted key sits at the back,pop(0)always removes an older key rather than the entry just inserted:def put(self, key: int, value: int) -> None: # Phase 1: if `key` already exists, overwrite its value, refresh its recency, # and return early so updating a full store never triggers an eviction. if key in self.values: self.values[key] = value self._mark_most_recent(key) return # Phase 2: insert a brand-new key at the most-recently-used end (back of list). self.values[key] = value self.recency_order.append(key) # Phase 3: if inserting pushed key count past `capacity`, evict the oldest key at index 0. # Because `capacity >= 1` and the new key is at the back, index 0 is always an older key. if len(self.values) > self.capacity: oldest_key = self.recency_order.pop(0) del self.values[oldest_key]- Existing key (update): Overwrite
Replay the operation list in `run_lru_store`
Finally,
run_lru_storeinstantiatesLRUStore(capacity), walkszip(operations, arguments), and records each return value (intfor"get",Nonefor"put"):def run_lru_store(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: store = LRUStore(capacity) # results: one output per operation (`int` for "get", `None` for "put") results: List[Optional[int]] = [] for operation, args in zip(operations, arguments): if operation == "get": key = args[0] results.append(store.get(key)) elif operation == "put": key, value = args[0], args[1] store.put(key, value) results.append(None) else: raise ValueError(f"Unknown operation: {operation}") return resultsTrace Example 1 step by step
Let us trace Example 1 with
capacity = 2(recency_orderlists keys from oldest on the left to newest on the right):Step Call Output values recency_order What happened ---- ------------ ------ ------------------ ------------- ----------------------------------------- 1 put(4, 400) None {4: 400} [4] Insert new key 4 2 put(7, 700) None {4: 400, 7: 700} [4, 7] Insert new key 7 (at capacity 2) 3 get(4) 400 {4: 400, 7: 700} [7, 4] Hit! Key 4 moves to newest end 4 put(9, 900) None {4: 400, 9: 900} [4, 9] Insert 9 -> [7, 4, 9] -> evict oldest (7) 5 get(7) -1 {4: 400, 9: 900} [4, 9] Miss! Key 7 was evicted; order unchanged 6 put(4, 450) None {4: 450, 9: 900} [9, 4] Update key 4 -> moves to newest, no evict 7 get(9) 900 {4: 450, 9: 900} [4, 9] Hit! Key 9 moves to newest end 8 get(4) 450 {4: 450, 9: 900} [9, 4] Hit! Returns updated value 450Collecting the
Outputcolumn gives[None, None, 400, None, -1, None, 900, 450], matching Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class LRUStore: """In-memory key-value store with least-recently-used (LRU) eviction.""" def __init__(self, capacity: int): self.capacity = capacity # values: dict mapping key -> stored value, e.g., {4: 400, 9: 900} self.values: Dict[int, int] = {} # recency_order: list of stored keys from oldest (index 0) to newest (index -1), e.g., [4, 9]. # Invariant: `values` and `recency_order` always contain the exact same set of keys. self.recency_order: List[int] = [] def _mark_most_recent(self, key: int) -> None: """Move an already-stored key to the newest end (back) of `recency_order`.""" self.recency_order.remove(key) self.recency_order.append(key) def get(self, key: int) -> int: # Check key membership with `in` (not value truthiness, since stored value 0 is valid). # A cache miss returns -1 and leaves `recency_order` completely unchanged. if key not in self.values: return -1 # A cache hit refreshes the key to most-recently-used before returning its value. self._mark_most_recent(key) return self.values[key] def put(self, key: int, value: int) -> None: # Phase 1: if `key` already exists, overwrite its value, refresh its recency, # and return early so updating a full store never triggers an eviction. if key in self.values: self.values[key] = value self._mark_most_recent(key) return # Phase 2: insert a brand-new key at the most-recently-used end (back of list). self.values[key] = value self.recency_order.append(key) # Phase 3: if inserting pushed key count past `capacity`, evict the oldest key at index 0. # Because `capacity >= 1` and the new key is at the back, index 0 is always an older key. if len(self.values) > self.capacity: oldest_key = self.recency_order.pop(0) del self.values[oldest_key] def run_lru_store(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]: store = LRUStore(capacity) # results: one output per operation (`int` for "get", `None` for "put") results: List[Optional[int]] = [] for operation, args in zip(operations, arguments): if operation == "get": key = args[0] results.append(store.get(key)) elif operation == "put": key, value = args[0], args[1] store.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 narrow coat rack with capacity hooks arranged from left (oldest) to right (newest). Every time someone wears a coat already on the rack (get) or hangs up a coat (put), that coat goes onto the far-right hook. When a brand-new coat arrives and all hooks are full, the coat hanging on the far-left hook is guaranteed to be the one untouched for the longest time—so you perform eviction (discarding an entry to free capacity) on that leftmost coat.
A plain dictionary alone falls short because, although it looks up values in O(1) time, it cannot quickly tell which entry has sat idle the longest once capacity fills up. Conversely, evicting in FIFO (first-in, first-out) arrival order—without promoting entries when they are read or overwritten—purges hot keys that callers still read constantly. Combining a dictionary values ({key: value}) with a recency list recency_order ([oldest_key, ..., newest_key]) gives O(1) value lookups alongside an explicit oldest-to-newest queue.
Walk through the first 4 steps of Example 1 with capacity = 2:
put(4, 400):values = {4: 400},recency_order = [4].put(7, 700):values = {4: 400, 7: 700},recency_order = [4, 7](4is oldest,7is newest).get(4): cache hit (the requested key is present) -> returns400and moves4to the right end sorecency_order = [7, 4].put(9, 900): appends9to get[7, 4, 9](3keys >capacity = 2), pops leftmost key7, and deletes7fromvalues, leaving{4: 400, 9: 900}and[4, 9].
Complexity
- Time:
O(capacity)pergetorput, andO(m * capacity)acrossmcommands. Each dictionary lookup or write inself.valuesruns inO(1)average time, whereasself.recency_order.remove(key)scans up tocapacitykeys andself.recency_order.pop(0)shifts up tocapacityremaining keys—a linear per-operation cost explicitly permitted by this problem. - Space:
O(capacity)inside the cache (plusO(m)for the returnedresultslist), sinceself.valuesandself.recency_orderhold at mostcapacityentries between operations (and momentarilycapacity + 1right before eviction).
Edge cases
- Cache miss on
get: Whenkeyis absent fromself.values(a cache miss, meaning the requested key is not stored),getreturns-1and leavesself.recency_orderuntouched. - Overwriting an existing key at full capacity: Calling
put(key, new_value)for an already-cached key updates its value and promoteskeyto newest without evicting any entry (Example 3). capacity = 1: Every new distinct key immediately evicts the sole cached entry (Example 2).- Zero or negative keys and values: Keys and values such as
0or-5work identically to positive integers; testingkey not in self.valuesavoids confusing a stored value of0with a missing key (note that storing-1returns-1, matching the return specification). - Empty command list: When
operationsis[],run_lru_storereturns[].
Common mistakes
- Evicting before checking whether
keyalready exists input: Checkingif len(self.values) == self.capacity:at the start ofputmistakenly evicts a neighbor when overwriting an existing key in a full cache. - Skipping recency promotion on
gethits orputupdates: Omitting_mark_most_recentdegrades the cache into FIFO eviction by initial insertion order rather than last access time. - Touching
recency_orderon agetmiss: Appending or moving an absent key violates the invariant (a condition that remains true after every step) thatself.valuesandself.recency_orderhold the exact same keys. - Checking value truthiness (
if not self.values.get(key):): Because0is falsy in Python, a cached value of0would be misreported as-1. Always checkif key not in self.values:. - Forgetting
results.append(None)forput: The caller expects one output element per command; omittingNoneshifts every later output index.
Alternative approaches
1. collections.OrderedDict (O(1) average time per command). Python's built-in OrderedDict pairs a hash table with a doubly linked order in C, supporting move_to_end(key) and popitem(last=False) in O(1) time:
from collections import OrderedDict
class FastLRUStore:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = OrderedDict() # keys ordered from oldest (front) to newest (back)
def get(self, key: int) -> int:
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key: int, value: int) -> None:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False)
2. Hash map + custom doubly linked list (O(1) average time per command). When OrderedDict is off-limits and O(1) operations are required, pair a dictionary key -> node with a doubly linked list (a chain of nodes each holding key, value, prev, and next pointers) bracketed by two dummy sentinel nodes (head at the oldest end and tail at the newest end) to avoid None checks. Detaching a node and splicing it right before tail updates 4 pointers in O(1) time, while eviction detaches head.next and deletes head.next.key from the dictionary.
Follow-up questions
- How would you bring both
getandputdown fromO(capacity)toO(1)average time? Replace the Pythonlist(recency_order, which shifts elements linearly on removal) with a doubly linked list whose nodes are indexed directly by the dictionarykey -> node(or usecollections.OrderedDict). Direct node pointers let you splice a key out of its current spot and attach it to the newest end by rewiring four neighbor pointers inO(1)time without scanning. Storingkeyinside every linked-list node also lets eviction removehead.nextand delete its dictionary entry inO(1)time. - What synchronization design would allow multiple threads to read and write the cache safely under heavy contention? Because even a
gethit mutates recency order, a shared reader-writer lock cannot run cache hits concurrently—everygetandputneeds exclusive synchronization on the recency structure. To eliminate a single global-lock bottleneck under heavy multi-threaded traffic, hash keys acrossSindependent shards (hash(key) % S), where each shard is a self-contained cache withcapacity / Sslots and its own mutex lock. Requests landing on different shards execute in parallel, trading exact global recency order for a very close per-shard approximation. - How would you extend the cache so each entry also expires automatically after a configurable time-to-live (TTL)? Store an
expire_atdeadline alongside each cached value and apply lazy expiry (checkingnow >= expire_atinsideget, deleting the stale entry and returning-1on sight). Because unread expired entries would otherwise hog capacity slots and cause live keys to be evicted prematurely,putshould purge expired entries before evicting valid ones—for example, by walking from the oldest end when all entries share a fixed TTL, or by maintaining a min-heap of(expire_at, key)pairs when per-key TTLs differ.
Follow-up questions
- How would you bring both `get` and `put` down from `O(capacity)` to `O(1)` average time?
- What synchronization design would allow multiple threads to read and write the cache safely under heavy contention?
- How would you extend the cache so each entry also expires automatically after a configurable time-to-live (TTL)?
Similar questions
- Numerically Stable Softmax
- End-to-End PPO Training and Sim-to-Real Architecture
- ML Background Walkthrough, Role Alignment, and First-Year Impact Plan
- Foundations of PPO and Transformer Sequence Models
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger