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]): If key is currently stored, promote key to the most-recently-accessed position and append its stored integer value to the output list. If key is not stored, leave recency order unchanged and append -1.
  • "put" (arguments[i] = [key, value]): If key is already stored, replace its value with value, promote key to the most-recently-accessed position without evicting any key, and append None. If key is new, insert (key, value) at the most-recently-accessed position; if the cache now holds more than capacity keys, remove the key whose latest read hit or write happened furthest in the past, and append None.

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 <= 1000
  • 0 <= 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

  1. Understand the input, output, and eviction rule

    We need to simulate an in-memory cache holding at most capacity distinct keys (capacity >= 1). Whenever inserting a brand-new key pushes the key count above capacity, 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 capacity along with two parallel lists, operations and arguments, and expects one result entry per command:

    • "get" with [key] appends the stored integer value when key is cached, or -1 when it is absent.
    • "put" with [key, value] inserts or updates key and appends None.
    capacity   = 2
    operations = ["put",    "put",    "get", "put",    "get"]
    arguments  = [[4, 400], [7, 700], [4],   [9, 900], [7]  ]
    results    = [None,     None,     400,   None,     -1   ]
    
  2. 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:

    1. get(key) when key is cached (a cache hit): Return its value and promote key to the most-recently-used position.
    2. get(key) when key is missing (a cache miss): Return -1 and change nothing—missing keys are never added to recency order.
    3. put(key, value) when key is already cached: Overwrite its value, promote key to the most-recently-used position, and evict nothing because the distinct key count did not grow.
    4. put(key, value) when key is new: Insert key at the most-recently-used position. Only if the distinct key count now exceeds capacity, purge the single oldest key.
  3. Pair a dictionary with a recency list

    Each command requires two capabilities:

    1. Fast value lookup and update -> store self.values as a dictionary mapping key -> value.
    2. Oldest-to-newest key tracking -> store self.recency_order as a list where index 0 (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.values and self.recency_order always hold the exact same set of keys. Moving an element in a Python list (remove + append, or pop(0)) shifts up to capacity elements in O(capacity) time, which this problem explicitly permits.

  4. Implement initialization, recency refresh, and `get`

    Centralizing the "remove and re-append to the back" step inside _mark_most_recent ensures get hits and put updates refresh keys identically. Notice that get checks if key not in self.values: rather than testing value truthiness, because 0 is 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]
    
  5. Implement `put`: separate updates from new insertions

    Inside put(key, value), check whether key is already in self.values before 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 key to self.values and append it to the back of self.recency_order. If len(self.values) > self.capacity, pop index 0 from self.recency_order and delete oldest_key from self.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 values
    

    Because capacity >= 1 and 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]
    
  6. Replay the operation list in `run_lru_store`

    Finally, run_lru_store instantiates LRUStore(capacity), walks zip(operations, arguments), and records each return value (int for "get", None for "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 results
    
  7. Trace Example 1 step by step

    Let us trace Example 1 with capacity = 2 (recency_order lists 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 450
    

    Collecting the Output column gives [None, None, 400, None, -1, None, 900, 450], matching Example 1.

  8. 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:

  1. put(4, 400): values = {4: 400}, recency_order = [4].
  2. put(7, 700): values = {4: 400, 7: 700}, recency_order = [4, 7] (4 is oldest, 7 is newest).
  3. get(4): cache hit (the requested key is present) -> returns 400 and moves 4 to the right end so recency_order = [7, 4].
  4. put(9, 900): appends 9 to get [7, 4, 9] (3 keys > capacity = 2), pops leftmost key 7, and deletes 7 from values, leaving {4: 400, 9: 900} and [4, 9].

Complexity

  • Time: O(capacity) per get or put, and O(m * capacity) across m commands. Each dictionary lookup or write in self.values runs in O(1) average time, whereas self.recency_order.remove(key) scans up to capacity keys and self.recency_order.pop(0) shifts up to capacity remaining keys—a linear per-operation cost explicitly permitted by this problem.
  • Space: O(capacity) inside the cache (plus O(m) for the returned results list), since self.values and self.recency_order hold at most capacity entries between operations (and momentarily capacity + 1 right before eviction).

Edge cases

  • Cache miss on get: When key is absent from self.values (a cache miss, meaning the requested key is not stored), get returns -1 and leaves self.recency_order untouched.
  • Overwriting an existing key at full capacity: Calling put(key, new_value) for an already-cached key updates its value and promotes key to 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 0 or -5 work identically to positive integers; testing key not in self.values avoids confusing a stored value of 0 with a missing key (note that storing -1 returns -1, matching the return specification).
  • Empty command list: When operations is [], run_lru_store returns [].

Common mistakes

  • Evicting before checking whether key already exists in put: Checking if len(self.values) == self.capacity: at the start of put mistakenly evicts a neighbor when overwriting an existing key in a full cache.
  • Skipping recency promotion on get hits or put updates: Omitting _mark_most_recent degrades the cache into FIFO eviction by initial insertion order rather than last access time.
  • Touching recency_order on a get miss: Appending or moving an absent key violates the invariant (a condition that remains true after every step) that self.values and self.recency_order hold the exact same keys.
  • Checking value truthiness (if not self.values.get(key):): Because 0 is falsy in Python, a cached value of 0 would be misreported as -1. Always check if key not in self.values:.
  • Forgetting results.append(None) for put: The caller expects one output element per command; omitting None shifts 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 get and put down from O(capacity) to O(1) average time? Replace the Python list (recency_order, which shifts elements linearly on removal) with a doubly linked list whose nodes are indexed directly by the dictionary key -> node (or use collections.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 in O(1) time without scanning. Storing key inside every linked-list node also lets eviction remove head.next and delete its dictionary entry in O(1) time.
  • What synchronization design would allow multiple threads to read and write the cache safely under heavy contention? Because even a get hit mutates recency order, a shared reader-writer lock cannot run cache hits concurrently—every get and put needs exclusive synchronization on the recency structure. To eliminate a single global-lock bottleneck under heavy multi-threaded traffic, hash keys across S independent shards (hash(key) % S), where each shard is a self-contained cache with capacity / S slots 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_at deadline alongside each cached value and apply lazy expiry (checking now >= expire_at inside get, deleting the stale entry and returning -1 on sight). Because unread expired entries would otherwise hog capacity slots and cause live keys to be evicted prematurely, put should 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

Similar questions

More XPeng interview questions

All 5 XPeng questions →