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:

  1. "put" with [key, value] (records None):
    • If capacity <= 0, nothing is stored.
    • Otherwise, associate key with value (overwriting its prior value if key is already cached) and promote key to most recently used.
    • If the number of stored keys now exceeds capacity, evict the single least recently used key.
  2. "get" with [key]:
    • If key is currently cached, promote key to most recently used and record its associated value.
    • If key is absent, leave recency order unchanged and record None.
  3. "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 via str(...).
    • Return "" if the cache is empty. Inspecting a snapshot does not count as accessing any key and must not alter recency order.
  4. "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.

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^4
  • 1 <= 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

  1. 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) inserts key or updates its existing value, marks key as the most recently used, and evicts the least recently used key if the cache now exceeds capacity (returns None).
    • get(key) returns the stored value for key and marks key as the most recently used, or returns None if key is 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: 10
    

    Two 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), so None cleanly signals a miss.

  2. 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. Every get or put then scans the list to find key, deletes it from the middle, and appends it to the end—which takes O(capacity) time per call.

    To make both get and put run in O(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 standard collections.OrderedDict bundles 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 OrderedDict is 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.

  3. Implement the LRU cache without disturbing recency on reads

    Let's write LRUCache carefully around three edge cases: - capacity <= 0: a cache of capacity 0 cannot hold anything, so put returns right away. - Updating an existing key: writing self.entries[key] = value before checking len(self.entries) > self.capacity ensures updating an already-stored key refreshes its recency without evicting anything. - Read-only iteration: items_most_recent_first walks reversed(self.entries) (newest to oldest) and looks up self.entries[key] directly instead of calling self.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 pairs
    
  4. Build the plain snapshot

    With items_most_recent_first() already yielding (key, value) pairs from newest to oldest, snapshot(cache) simply formats each pair as f"{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)
    
  5. 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: 10
    

    There 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], then 10 [u3, u1], then 20 [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-adjacent u3 and u1 across 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 dict preserves key insertion order. So as we scan cache.items_most_recent_first() from newest to oldest, inserting each value into keys_by_value the 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 results
    
  6. Trace Example 2 step by step

    Let's trace capacity = 2 on put('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 and put('k3', 5) would have evicted 'k1' instead of 'k2'.

  7. 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).

  • get and put:
    • Time: O(1) average per call. Looking up a key in OrderedDict, unlinking and relinking its doubly-linked-list node via move_to_end, and evicting the oldest node via popitem(last=False) each do a constant number of hash-table and pointer steps.
    • Space: O(capacity) total across the lifetime of the cache, since self.entries never retains more than capacity key-value pairs at once.
  • snapshot and compressed_snapshot:
    • Time: O(k) (plus total string length of the formatted keys and values). We walk the k entries once in reverse order; compressed_snapshot also performs one O(1) average dictionary lookup/append per entry and iterates over at most k value groups.
    • Space: O(k) temporary space to hold the list of (key, value) pairs, the keys_by_value grouping dictionary, and the output lines.

Edge cases

  • Empty cache: Both snapshot and compressed_snapshot return "" (empty string), never "\n" or None.
  • capacity == 0: put returns immediately, the cache remains empty, every get returns None, and snapshots return "".
  • Updating an existing key at full capacity: put overwrites the value and refreshes recency without growing len(self.entries), so no other entry is evicted.
  • get on a missing or already-evicted key: Returns None without modifying any stored entry's recency.
  • Snapshots do not count as accesses: Calling snapshot or compressed_snapshot reads self.entries[key] directly rather than calling cache.get(key), so the next eviction still drops the true oldest key.
  • Mixed key and value types: Formatting with str handles integer keys (7) and string values ("red") identically ("7: red" and "red [7]").

Common mistakes

  • Evicting before checking whether key already exists: If you evict whenever len(entries) == capacity before inserting, updating an existing key in a full cache wrongly drops another valid key.
  • Iterating OrderedDict forward instead of in reverse: OrderedDict yields keys from oldest to newest, whereas cache snapshots conventionally list the most recently used item first (reversed(self.entries)).
  • Calling cache.get(key) inside snapshot: Because get calls move_to_end, reading entries through get scrambles recency order as a side effect of printing!
  • Grouping compressed keys in a set or 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 (head and tail, placeholder nodes at both ends that eliminate None edge checks when unlinking or inserting). This achieves the exact same O(1) bounds without OrderedDict and is standard when an interviewer asks you to implement the pointers yourself.
  • Plain Python dict: Python 3.7+ dicts preserve insertion order, so val = d.pop(key); d[key] = val moves a key to the end and next(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 degrade next(iter(d)) beyond strict O(1) under heavy churn; OrderedDict maintains a real doubly linked list so popitem(last=False) is always O(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 list or dict directly as a key in keys_by_value raises TypeError: unhashable type. To group equal unhashable values cleanly, convert each value into a canonical hashable representation—for instance json.dumps(value, sort_keys=True) for JSON-compatible values, or a recursive frozen tuple/frozenset structure—and map canonical_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 in O(1) by caching last_snapshot and last_compressed alongside a boolean is_dirty flag. Set is_dirty = True on every put and every cache-hit get (cache-miss get leaves is_dirty untouched), and regenerate the cached strings only when is_dirty is True.
  • What locking or sharding strategy would make the cache and its snapshots safe under multi-threaded access? Because even a cache-hit get mutates the recency list (move_to_end), a reader-writer lock cannot run get calls concurrently; the simplest correct design wraps get, put, and items_most_recent_first in a single threading.Lock so snapshots observe an atomic point-in-time state. Under heavy multi-core contention, lock sharding partitions keys via hash(key) % num_shards across S independent LRUCache(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

Similar questions

More Hebbia interview questions

All 6 Hebbia questions →