LRU Cache With Value-Grouped Snapshots
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Design a fixed-capacity Least Recently Used (LRU) key-value cache paired with two read-only string formatters—one listing individual entries and one collapsing entries that hold identical values—exposed through run_cache_operations:
def run_cache_operations(
capacity: int,
operations: List[str],
arguments: List[List[object]],
) -> List[object]:
Cache & Formatter Semantics
Initialize an empty cache with maximum size capacity, then process each (op, args) command in sequence and return the list of per-command results:
"put"with[key, value](recordsNone):- If
capacity <= 0, nothing is stored. - Otherwise, associate
keywithvalue(overwriting its prior value ifkeyis already cached) and promotekeyto most recently used. - If the number of stored keys now exceeds
capacity, evict the single least recently used key.
- If
"get"with[key]:- If
keyis currently cached, promotekeyto most recently used and record its associated value. - If
keyis absent, leave recency order unchanged and recordNone.
- If
"snapshot"with[]:- Return a
"\n"-separated string of"<key>: <value>"lines ordered from most recently used (top line) to least recently used (bottom line), formatting keys and values viastr(...). - Return
""if the cache is empty. Inspecting a snapshot does not count as accessing any key and must not alter recency order.
- Return a
"compressed_snapshot"with[]:- Collapse all cached keys that map to equal values onto a single line formatted as
"<value> [<k1>, <k2>, ...]"(joined across groups by"\n", or""when empty), without altering recency order:- Between groups: order distinct value lines from top to bottom according to each value's most recently used key (newest group first).
- Within each group: list
<k1>, <k2>, ...from most recently used to least recently used.
- Collapse all cached keys that map to equal values onto a single line formatted as
Examples
Example 1
Input:
capacity = 3
operations = ["put", "put", "put", "snapshot", "compressed_snapshot"]
arguments = [["u1", 10], ["u2", 20], ["u3", 10], [], []]
Output:
[None, None, None, "u3: 10\nu2: 20\nu1: 10", "10 [u3, u1]\n20 [u2]"]
After the three inserts, recency from newest to oldest is u3 (10), u2 (20), u1 (10). Plain snapshot emits those three "key: value" lines in newest-to-oldest order. In compressed_snapshot, value 10 appears first at u3 (so 10 [u3, u1] comes first, keeping u3 ahead of u1), followed by 20 [u2].
Example 2
Input:
capacity = 2
operations = ["put", "put", "get", "put", "get", "snapshot", "compressed_snapshot"]
arguments = [["k1", 5], ["k2", 9], ["k1"], ["k3", 5], ["k2"], [], []]
Output:
[None, None, 5, None, None, "k3: 5\nk1: 5", "5 [k3, k1]"]
Inserting k1 then k2 fills the capacity-2 cache (k2 newest, k1 oldest). Reading get("k1") returns 5 and promotes k1 above k2, so the subsequent put("k3", 5) evicts k2. get("k2") then misses (None), and the remaining entries k3 (newest) and k1 (oldest) share value 5, producing "k3: 5\nk1: 5" and "5 [k3, k1]".
Constraints
0 <= capacity <= 10^41 <= len(operations) == len(arguments) <= 10^4- Every operation name is
"put","get","snapshot", or"compressed_snapshot". - Cached keys and values are hashable Python objects (such as strings and integers).
Step-by-step walkthrough
Understand the cache rules and snapshot formats
We need to build a Least Recently Used (LRU) cache—a bounded key-value store that evicts the entry untouched for the longest time whenever capacity is exceeded—along with two side-effect-free printers:
put(key, value)insertskeyor updates its existing value, markskeyas the most recently used, and evicts the least recently used key if the cache now exceedscapacity(returnsNone).get(key)returns the stored value forkeyand markskeyas the most recently used, or returnsNoneifkeyis missing.snapshot(cache)returns one"key: value"line per entry from most recently used to least recently used, separated by"\n"(or""if the cache is empty).compressed_snapshot(cache)groups entries that share the same value into"value [key1, key2, ...]"lines while preserving recency order.
Plain snapshot (newest -> oldest): Compressed snapshot: u3: 10 10 [u3, u1] u2: 20 ===> 20 [u2] u1: 10Two important invariants keep behaviour predictable: 1. Snapshots are read-only: printing the cache never counts as "using" a key, so recency order does not change. 2. Missing keys return
None: unlike integer-only cache problems that return-1, values here can be any type (including-1), soNonecleanly signals a miss.Why a plain list is too slow, and how OrderedDict gives O(1)
A brute-force cache keeps a Python list of
[key, value]pairs from oldest to newest. Everygetorputthen scans the list to findkey, deletes it from the middle, and appends it to the end—which takesO(capacity)time per call.To make both
getandputrun inO(1)average time, we combine a hash map (for instant key lookup) with a doubly linked list (where each entry points to its previous and next neighbours so moving an entry to the end or dropping the oldest entry only rewires a few pointers). Python's standardcollections.OrderedDictbundles this exact pair out of the box:OrderedDict layout: front (oldest / evicted next) back (newest / most recent) [ u1: 10 ] <------> [ u2: 20 ] <------> [ u3: 10 ] ^ ^ popitem(last=False) move_to_end(key) evicts front in O(1) moves accessed key here in O(1)In an interview, state clearly that
OrderedDictis backed by a hash table plus a doubly linked list, and offer to write the node class manually if the interviewer wants to see pointer manipulation.Implement the LRU cache without disturbing recency on reads
Let's write
LRUCachecarefully around three edge cases: -capacity <= 0: a cache of capacity0cannot hold anything, soputreturns right away. - Updating an existing key: writingself.entries[key] = valuebefore checkinglen(self.entries) > self.capacityensures updating an already-stored key refreshes its recency without evicting anything. - Read-only iteration:items_most_recent_firstwalksreversed(self.entries)(newest to oldest) and looks upself.entries[key]directly instead of callingself.get(key), leaving recency completely untouched.from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity # entries: OrderedDict mapping key -> value from oldest (front) to newest (back). self.entries: OrderedDict = OrderedDict() def get(self, key: object) -> object: """Return the value for `key` and refresh its recency, or None if missing.""" if key not in self.entries: return None # Move accessed key to the back so it becomes the most recently used entry. self.entries.move_to_end(key) return self.entries[key] def put(self, key: object, value: object) -> None: """Insert or update `key`, mark it most recent, and evict oldest if over capacity.""" if self.capacity <= 0: return # Write first and move to back; updating an existing key does not increase len(entries). self.entries[key] = value self.entries.move_to_end(key) if len(self.entries) > self.capacity: # last=False pops from the front, evicting the least recently used key in O(1). self.entries.popitem(last=False) def items_most_recent_first(self) -> List[Tuple[object, object]]: """Return (key, value) pairs newest-to-oldest without altering recency order.""" pairs: List[Tuple[object, object]] = [] # Read self.entries[key] directly instead of self.get(key) so snapshots are side-effect-free. for key in reversed(self.entries): pairs.append((key, self.entries[key])) return pairsBuild the plain snapshot
With
items_most_recent_first()already yielding(key, value)pairs from newest to oldest,snapshot(cache)simply formats each pair asf"{key}: {value}"and joins them with"\n". When the cache is empty,"\n".join([])cleanly returns"".def snapshot(cache: LRUCache) -> str: """Format cache contents as 'key: value' lines from most to least recently used.""" lines: List[str] = [] for key, value in cache.items_most_recent_first(): lines.append(f"{key}: {value}") return "\n".join(lines)Clarify and implement compressed snapshot ordering
Let's examine how group ordering works when several distinct values sit interleaved inside the cache. Suppose the plain snapshot (newest to oldest) is:
Plain snapshot (newest -> oldest): 1st: u4: 30 2nd: u3: 10 3rd: u2: 20 4th: u1: 10There are three candidate rules we could discuss with an interviewer: 1. Order groups by each value's most recent key, and order keys within each group from newest to oldest:
30 [u4], then10 [u3, u1], then20 [u2]. 2. Merge only adjacent equal values (run-length encoding):30 [u4],10 [u3],20 [u2],10 [u1]—preserves exact row adjacency, but splits non-adjacentu3andu1across two lines. 3. Sort groups by value:10 [u3, u1],20 [u2],30 [u4]—destroys recency information across groups.Rule 1 gives every distinct value exactly one line, keeps keys inside
[u3, u1]in newest-to-oldest order, and ensures the leading (newest) key of each line top-to-bottom (u4,u3,u2) follows strict recency order!Even better, Python
dictpreserves key insertion order. So as we scancache.items_most_recent_first()from newest to oldest, inserting eachvalueintokeys_by_valuethe first time we see it automatically anchors that value's group at its most recent key:def compressed_snapshot(cache: LRUCache) -> str: """Group keys sharing the same value as 'value [k1, k2, ...]' in recency order.""" # keys_by_value: dict mapping value -> [str(key), ...] ordered by each value's newest key. keys_by_value: Dict[object, List[str]] = {} for key, value in cache.items_most_recent_first(): # Python dicts preserve insertion order, so each value stays at its first-seen (newest) slot. if value not in keys_by_value: keys_by_value[value] = [] keys_by_value[value].append(str(key)) lines: List[str] = [] for value, key_list in keys_by_value.items(): joined_keys = ", ".join(key_list) lines.append(f"{value} [{joined_keys}]") return "\n".join(lines) def run_cache_operations( capacity: int, operations: List[str], arguments: List[List[object]] ) -> List[object]: # Execute each cache or snapshot operation in order and collect its return value. cache = LRUCache(capacity) results: List[object] = [] 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])) elif op == "snapshot": results.append(snapshot(cache)) elif op == "compressed_snapshot": results.append(compressed_snapshot(cache)) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 2 step by step
Let's trace
capacity = 2onput('k1', 5),put('k2', 9),get('k1'),put('k3', 5),get('k2'),snapshot(),compressed_snapshot():Operation OrderedDict (oldest -> newest) Return value --------------------- -------------------------------------- ---------------- put('k1', 5) [k1: 5] None put('k2', 9) [k1: 5, k2: 9] None get('k1') [k2: 9, k1: 5] (k1 moves to newest!) 5 put('k3', 5) [k2: 9, k1: 5, k3: 5] -> evicts oldest k2 [k1: 5, k3: 5] None get('k2') [k1: 5, k3: 5] (miss, unchanged) None snapshot() [k1: 5, k3: 5] (unchanged) "k3: 5\nk1: 5" compressed_snapshot() [k1: 5, k3: 5] (unchanged) "5 [k3, k1]"Notice how
get('k1')saved'k1'from eviction: without that read,'k1'would still sit at the front andput('k3', 5)would have evicted'k1'instead of'k2'.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity # entries: OrderedDict mapping key -> value from oldest (front) to newest (back). self.entries: OrderedDict = OrderedDict() def get(self, key: object) -> object: """Return the value for `key` and refresh its recency, or None if missing.""" if key not in self.entries: return None # Move accessed key to the back so it becomes the most recently used entry. self.entries.move_to_end(key) return self.entries[key] def put(self, key: object, value: object) -> None: """Insert or update `key`, mark it most recent, and evict oldest if over capacity.""" if self.capacity <= 0: return # Write first and move to back; updating an existing key does not increase len(entries). self.entries[key] = value self.entries.move_to_end(key) if len(self.entries) > self.capacity: # last=False pops from the front, evicting the least recently used key in O(1). self.entries.popitem(last=False) def items_most_recent_first(self) -> List[Tuple[object, object]]: """Return (key, value) pairs newest-to-oldest without altering recency order.""" pairs: List[Tuple[object, object]] = [] # Read self.entries[key] directly instead of self.get(key) so snapshots are side-effect-free. for key in reversed(self.entries): pairs.append((key, self.entries[key])) return pairs def snapshot(cache: LRUCache) -> str: """Format cache contents as 'key: value' lines from most to least recently used.""" lines: List[str] = [] for key, value in cache.items_most_recent_first(): lines.append(f"{key}: {value}") return "\n".join(lines) def compressed_snapshot(cache: LRUCache) -> str: """Group keys sharing the same value as 'value [k1, k2, ...]' in recency order.""" # keys_by_value: dict mapping value -> [str(key), ...] ordered by each value's newest key. keys_by_value: Dict[object, List[str]] = {} for key, value in cache.items_most_recent_first(): # Python dicts preserve insertion order, so each value stays at its first-seen (newest) slot. if value not in keys_by_value: keys_by_value[value] = [] keys_by_value[value].append(str(key)) lines: List[str] = [] for value, key_list in keys_by_value.items(): joined_keys = ", ".join(key_list) lines.append(f"{value} [{joined_keys}]") return "\n".join(lines) def run_cache_operations( capacity: int, operations: List[str], arguments: List[List[object]] ) -> List[object]: # Execute each cache or snapshot operation in order and collect its return value. cache = LRUCache(capacity) results: List[object] = [] 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])) elif op == "snapshot": results.append(snapshot(cache)) elif op == "compressed_snapshot": results.append(compressed_snapshot(cache)) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a stack of file folders on your desk that has room for at most capacity folders. Every time you open an existing folder (get) or add/update one (put), you place that folder right on top of the stack; if the stack grows taller than capacity, the untouched folder at the very bottom—the Least Recently Used (LRU) entry—is removed. Taking a snapshot simply reads the folder labels from top (newest) to bottom (oldest) without moving any folders, while compressed_snapshot bundles folders that hold the same value onto a single summary line anchored where that value first appeared from the top.
Why does a naive array implementation fall short? If you store [key, value] pairs in a plain list, every get and put has to scan up to capacity items to locate a key and shift elements to move it to the top, slowing O(1) cache operations down to O(capacity). And when building the compressed snapshot, tossing keys into an unordered set or sorting groups alphabetically throws away the recency order the caller asked to inspect.
To get O(1) updates and clean snapshots, we use Python's OrderedDict—a hash table paired with a doubly linked list (a chain of nodes where each node points to both its neighbours so moving an item to the end or popping the front takes constant time). Let's trace 4 operations with capacity = 3:
1. put('u1', 10) -> [u1:10]
2. put('u2', 20) -> [u1:10, u2:20]
3. put('u3', 10) -> [u1:10, u2:20, u3:10] (newest is u3, oldest is u1)
4. get('u2') -> [u1:10, u3:10, u2:20] (u2 jumps to newest!)
snapshot() reads newest -> oldest:
u2: 20
u3: 10
u1: 10
compressed_snapshot() groups by first-seen value from newest -> oldest:
value 20 seen first at u2 -> 20 [u2]
value 10 seen first at u3, then u1 -> 10 [u3, u1]
Complexity
Let k be the current number of entries in the cache (k <= capacity).
getandput:- Time:
O(1)average per call. Looking up a key inOrderedDict, unlinking and relinking its doubly-linked-list node viamove_to_end, and evicting the oldest node viapopitem(last=False)each do a constant number of hash-table and pointer steps. - Space:
O(capacity)total across the lifetime of the cache, sinceself.entriesnever retains more thancapacitykey-value pairs at once.
- Time:
snapshotandcompressed_snapshot:- Time:
O(k)(plus total string length of the formatted keys and values). We walk thekentries once in reverse order;compressed_snapshotalso performs oneO(1)average dictionary lookup/append per entry and iterates over at mostkvalue groups. - Space:
O(k)temporary space to hold the list of(key, value)pairs, thekeys_by_valuegrouping dictionary, and the output lines.
- Time:
Edge cases
- Empty cache: Both
snapshotandcompressed_snapshotreturn""(empty string), never"\n"orNone. capacity == 0:putreturns immediately, the cache remains empty, everygetreturnsNone, and snapshots return"".- Updating an existing key at full capacity:
putoverwrites the value and refreshes recency without growinglen(self.entries), so no other entry is evicted. geton a missing or already-evicted key: ReturnsNonewithout modifying any stored entry's recency.- Snapshots do not count as accesses: Calling
snapshotorcompressed_snapshotreadsself.entries[key]directly rather than callingcache.get(key), so the next eviction still drops the true oldest key. - Mixed key and value types: Formatting with
strhandles integer keys (7) and string values ("red") identically ("7: red"and"red [7]").
Common mistakes
- Evicting before checking whether
keyalready exists: If you evict wheneverlen(entries) == capacitybefore inserting, updating an existing key in a full cache wrongly drops another valid key. - Iterating
OrderedDictforward instead of in reverse:OrderedDictyields keys from oldest to newest, whereas cache snapshots conventionally list the most recently used item first (reversed(self.entries)). - Calling
cache.get(key)insidesnapshot: Becausegetcallsmove_to_end, reading entries throughgetscrambles recency order as a side effect of printing! - Grouping compressed keys in a
setor sorting groups by value: Sets lose key recency order inside[...], and sorting by value loses recency order across lines. - Appending a trailing newline
"\n": Joining lines with"\n".join(lines)avoids a spurious trailing newline on non-empty output and produces""on empty output.
Alternative approaches
- Custom hash map + doubly linked list with sentinel nodes: Maintain
nodes = {key: Node}alongside a doubly linked list bounded by two dummy sentinel nodes (headandtail, placeholder nodes at both ends that eliminateNoneedge checks when unlinking or inserting). This achieves the exact sameO(1)bounds withoutOrderedDictand is standard when an interviewer asks you to implement the pointers yourself. - Plain Python
dict: Python 3.7+ dicts preserve insertion order, soval = d.pop(key); d[key] = valmoves a key to the end andnext(iter(d))finds the oldest key. However, repeated deletions leave dummy tombstones at the front of CPython's internal array until a resize occurs, which can degradenext(iter(d))beyond strictO(1)under heavy churn;OrderedDictmaintains a real doubly linked list sopopitem(last=False)is alwaysO(1). - Run-length compression: Run-length encoding merges only consecutive entries that share the same value (
u3: 10, u2: 20, u1: 10->10 [u3],20 [u2],10 [u1]). It preserves exact neighbour positions if a caller needs lossless order reconstruction, though it produces duplicate value rows.
Follow-up questions
- How would you group equal values in compressed snapshots when cached values can be unhashable containers such as lists or dictionaries? Putting a
listordictdirectly as a key inkeys_by_valueraisesTypeError: unhashable type. To group equal unhashable values cleanly, convert each value into a canonical hashable representation—for instancejson.dumps(value, sort_keys=True)for JSON-compatible values, or a recursive frozen tuple/frozenset structure—and mapcanonical_key -> (original_value, [key_strings])so each group still formats using its original value representation. - How can you avoid rebuilding snapshot strings from scratch when read-only snapshot calls vastly outnumber cache writes and hits? Creating a fresh string takes
O(k)work whenever cache contents or recency actually change, but repeated snapshot reads with no intervening state change can run inO(1)by cachinglast_snapshotandlast_compressedalongside a booleanis_dirtyflag. Setis_dirty = Trueon everyputand every cache-hitget(cache-missgetleavesis_dirtyuntouched), and regenerate the cached strings only whenis_dirtyisTrue. - What locking or sharding strategy would make the cache and its snapshots safe under multi-threaded access? Because even a cache-hit
getmutates the recency list (move_to_end), a reader-writer lock cannot rungetcalls concurrently; the simplest correct design wrapsget,put, anditems_most_recent_firstin a singlethreading.Lockso snapshots observe an atomic point-in-time state. Under heavy multi-core contention, lock sharding partitions keys viahash(key) % num_shardsacrossSindependentLRUCache(capacity // S)shards—each guarded by its own lock and monotonic access counter—and merges shard entries by counter order when a global snapshot is requested.
Follow-up questions
- How would you group equal values in compressed snapshots when cached values can be unhashable containers such as lists or dictionaries?
- How can you avoid rebuilding snapshot strings from scratch when read-only snapshot calls vastly outnumber cache writes and hits?
- What locking or sharding strategy would make the cache and its snapshots safe under multi-threaded access?
Similar questions
- 3x3 Tic-Tac-Toe Grid Winner Check
- Nested 3x3 Ultimate Tic-Tac-Toe Engine
- Backend Architecture for a Multi-Agent Fintech Assistant
- Multi-Agent Corpus Research and Grounded Charting Platform
- Design a Cited Q&A Assistant over SEC Filings
- 2D Max Pooling with Source Coordinates