Constant-Time LRU Key-Value Cache

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Build a bounded in-memory key-value store governed by the Least Recently Used (LRU) eviction rule, and expose a batch runner lru_cache_operations(capacity, operations, arguments) that replays a sequence of lookups and writes against a fresh cache of size capacity.

Cache Behavior

An LRUCache(capacity) instance holds up to capacity distinct integer keys mapped to integer values, tracking recency across every successful read and write:

  • get(key) -> int: When key is currently resident, mark key as the most recently touched entry and return its associated value. When key is absent, return -1 without modifying resident entries or their recency order.
  • put(key, value) -> None:
    • When key is already resident, overwrite its stored value with value and promote key to the most recently touched position (no eviction occurs).
    • When key is not resident and the store already holds capacity keys, evict whichever resident key was touched least recently (considering both get hits and put calls), then insert (key, value) at the most recently touched position.
class LRUCache:
    def __init__(self, capacity: int):
        pass

    def get(self, key: int) -> int:
        pass

    def put(self, key: int, value: int) -> None:
        pass

Batch Runner Signature

def lru_cache_operations(
    capacity: int,
    operations: List[str],
    arguments: List[List[int]],
) -> List[Optional[int]]:
    pass

Create one LRUCache(capacity) and execute (operations[i], arguments[i]) in order:

  • "get" with [key]: Append the integer returned by cache.get(key).
  • "put" with [key, value]: Call cache.put(key, value) and append None.

Examples

Example 1

capacity = 2
operations = ["put", "put", "get", "put", "get", "get", "put", "get", "get"]
arguments = [[10, 50], [20, 60], [10], [30, 70], [20], [10], [40, 80], [30], [10]]
# Output: [None, None, 50, None, -1, 50, None, -1, 50]

Walk-through: After put(10, 50) and put(20, 60), key 10 is older than 20. Calling get(10) returns 50 and refreshes 10, making 20 the oldest entry. Inserting 30 evicts 20, so get(20) returns -1. Next get(10) returns 50 and refreshes 10 again, so put(40, 80) evicts 30 (get(30) -> -1) while 10 remains (get(10) -> 50).

Example 2

capacity = 2
operations = ["put", "put", "put", "put", "get", "get"]
arguments = [[5, 12], [8, 24], [5, 99], [9, 36], [5], [8]]
# Output: [None, None, None, None, 99, -1]

Walk-through: put(5, 12) and put(8, 24) fill both slots. put(5, 99) updates existing key 5 in place without evicting 8 and promotes 5 ahead of 8. The subsequent put(9, 36) therefore evicts 8, leaving 5 -> 99 and 8 -> -1.

Example 3

capacity = 1
operations = ["get", "put", "get", "put", "get", "get"]
arguments = [[0], [0, 0], [0], [7, 45], [0], [7]]
# Output: [-1, None, 0, None, -1, 45]

Walk-through: An initial lookup on an empty cache returns -1. Key 0 with value 0 is stored and retrieved (0), then displaced by put(7, 45) because capacity == 1.

Constraints

  • 1 <= capacity <= 100,000
  • 0 <= key <= 1,000,000
  • 0 <= value <= 1,000,000,000
  • 0 <= len(operations) == len(arguments) <= 100,000
  • Both get and put must run in O(1) average time.

Step-by-step walkthrough

  1. Understand the LRU cache rules

    An LRU (Least Recently Used) cache stores at most capacity key-value pairs and remembers how recently each key was touched:

    • get(key): If key is in the cache, mark it as most recently used and return its value; if key is absent, return -1 without changing the order of anything.
    • put(key, value):
      • If key is already in the cache, update its value and mark it as most recently used (never evict anything on an overwrite).
      • If key is new and the cache is already at capacity, evict the least recently used key first, then insert (key, value) as the most recently used entry.

    The judge calls lru_cache_operations(capacity, operations, arguments) and expects one result per call (value or -1 for "get", None for "put"). With capacity up to 100,000, both get and put must run in O(1) average time.

  2. Why a plain list or plain dictionary is not enough

    Suppose we keep [key, value] pairs in a Python list ordered from oldest to newest. Finding a key or removing it from the middle shifts up to capacity elements — O(capacity) work per call, which balloons to 10^10 operations across 100,000 calls on a 100,000-item cache.

    On the other hand, a plain Python dictionary (dict) finds any key in O(1) average time, but by itself has no way to jump straight to an entry in the middle of a usage timeline and move it to the front without rebuilding order.

    To get O(1) for both lookup and reordering, we pair two classic data structures together.

  3. Combine a hash map with a sentinel doubly linked list

    Here is how each structure covers the other's blind spot:

    1. Doubly linked list (a chain of nodes where every node points to both prev and next): maintains the exact recency order from most recently used at the front to least recently used at the back. Given a direct reference to a node anywhere in the chain, splicing it out or inserting it at the front only rewires four neighbor pointers (O(1) time).
    2. Hash map (key_to_node dictionary): maps each key directly to its Node object inside the linked list in O(1) average time, so we never scan the list to find a node.

    Two small structural choices eliminate almost every bug:

    • Store key inside Node as well as value: When the cache is full, we find the victim at the back of the list (tail.prev). Having lru_node.key right on the node lets us run del self.key_to_node[lru_node.key] in O(1) time.
    • Keep two permanent dummy sentinel nodes (head and tail): head always sits before the newest node, and tail always sits after the oldest node. Because head and tail are never deleted, every real node always has a non-None prev and a non-None next — even when the cache is empty (head <-> tail) or holds a single item!
    key_to_node = { 10: ──┐,  30: ──────────┐ }
                          │                 │
                          v                 v
    [head] <───> [Node(10, 50)] <───> [Node(30, 70)] <───> [tail]
                   most recent          least recent
                   (head.next)           (tail.prev)
    
  4. Write bug-free `O(1)` pointer helpers

    Every cache operation reduces to two tiny list primitives: _remove(node) and _insert_after_head(node).

    Watch how _insert_after_head saves first_real = self.head.next in a named variable before changing any pointers — that prevents the classic bug of overwriting self.head.next first and losing the rest of the chain:

    Before _insert_after_head(node):
        [head] <───────────────────────> [first_real]
    
    After wiring the 4 links:
        [head] <───> [node] <───> [first_real]
    
    class Node:
        """One cached entry inside the doubly linked recency list."""
    
        def __init__(self, key: int, value: int):
            # Store `key` alongside `value` so evicting `tail.prev` tells us 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: maps int key -> its live Node in the doubly linked list for O(1) lookup.
            self.key_to_node: Dict[int, Node] = {}
    
            # Permanent dummy sentinels: `head <-> [most recent] <-> ... <-> [least recent] <-> tail`.
            # Keeping sentinels at both ends guarantees every real node has non-None `prev` and `next`.
            self.head = Node(-1, -1)
            self.tail = Node(-1, -1)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _remove(self, node: Node) -> None:
            # Splice `node` out of the list by wiring its left and right neighbors directly together.
            left_neighbor = node.prev
            right_neighbor = node.next
            assert left_neighbor is not None and right_neighbor is not None
            left_neighbor.next = right_neighbor
            right_neighbor.prev = left_neighbor
    
        def _insert_after_head(self, node: Node) -> None:
            # Place `node` right after `head` (the most-recently-used position).
            # Save `first_real` before overwriting `head.next` so we do not lose the rest of the list.
            first_real = self.head.next
            assert first_real is not None
            node.prev = self.head
            node.next = first_real
            self.head.next = node
            first_real.prev = node
    
  5. Implement `get` and `put`

    With _remove and _insert_after_head ready, get and put read like plain English:

    • get(key): Look up node = self.key_to_node.get(key). If node is None, return -1. Otherwise unlink node, re-insert it right after head, and return node.value.
    • put(key, value):
      1. Existing key: Update existing.value = value, move existing right after head, and return immediately.
      2. Full cache on a new key: When len(self.key_to_node) == self.capacity, evict lru_node = self.tail.prev from both the linked list and self.key_to_node before inserting.
      3. Insert new key: Create Node(key, value), store it in self.key_to_node[key], and insert it right after head.

    Notice we always check is None / is not None rather than truthiness, because key = 0 and value = 0 are allowed by the constraints (0 <= key, 0 <= value).

        def get(self, key: int) -> int:
            # Use `is None` (never truthiness) because key 0 and value 0 are valid cache entries.
            node = self.key_to_node.get(key)
            if node is None:
                return -1
    
            # A cache hit counts as a fresh use: move `node` to the most-recently-used front.
            self._remove(node)
            self._insert_after_head(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            # Phase 1: If `key` is already cached, overwrite its value and promote it to the front.
            existing = self.key_to_node.get(key)
            if existing is not None:
                existing.value = value
                self._remove(existing)
                self._insert_after_head(existing)
                return
    
            # Phase 2: Adding a brand-new key when full — evict the least recently used node (`tail.prev`)
            # BEFORE inserting, keeping peak resident count <= capacity.
            if len(self.key_to_node) == self.capacity:
                lru_node = self.tail.prev
                assert lru_node is not None and lru_node is not self.head
                self._remove(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Phase 3: Create the new node, register it in the map, and place it at the front.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._insert_after_head(new_node)
    
  6. Replay operations and trace Example 1

    lru_cache_operations instantiates LRUCache(capacity) and records each call's output. Here is the complete state trace on Example 1 (capacity = 2):

    Call         Recency list (head -> ... -> tail)        Output   Why
    ----------   ---------------------------------------   ------   --------------------------------------
    put(10,50)   head <-> (10:50) <-> tail                 None     insert 10
    put(20,60)   head <-> (20:60) <-> (10:50) <-> tail     None     insert 20 at front
    get(10)      head <-> (10:50) <-> (20:60) <-> tail      50      hit! 10 moves to front; 20 is now LRU
    put(30,70)   head <-> (30:70) <-> (10:50) <-> tail     None     full -> evict tail.prev (20), add 30
    get(20)      head <-> (30:70) <-> (10:50) <-> tail     -1       miss (20 was evicted)
    get(10)      head <-> (10:50) <-> (30:70) <-> tail      50      hit! 10 moves to front; 30 is now LRU
    put(40,80)   head <-> (40:80) <-> (10:50) <-> tail     None     full -> evict tail.prev (30), add 40
    get(30)      head <-> (40:80) <-> (10:50) <-> tail     -1       miss (30 was evicted)
    get(10)      head <-> (10:50) <-> (40:80) <-> tail      50      hit! 10 moves to front
    

    Result list: [None, None, 50, None, -1, 50, None, -1, 50].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        """One cached entry inside the doubly linked recency list."""
    
        def __init__(self, key: int, value: int):
            # Store `key` alongside `value` so evicting `tail.prev` tells us 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: maps int key -> its live Node in the doubly linked list for O(1) lookup.
            self.key_to_node: Dict[int, Node] = {}
    
            # Permanent dummy sentinels: `head <-> [most recent] <-> ... <-> [least recent] <-> tail`.
            # Keeping sentinels at both ends guarantees every real node has non-None `prev` and `next`.
            self.head = Node(-1, -1)
            self.tail = Node(-1, -1)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _remove(self, node: Node) -> None:
            # Splice `node` out of the list by wiring its left and right neighbors directly together.
            left_neighbor = node.prev
            right_neighbor = node.next
            assert left_neighbor is not None and right_neighbor is not None
            left_neighbor.next = right_neighbor
            right_neighbor.prev = left_neighbor
    
        def _insert_after_head(self, node: Node) -> None:
            # Place `node` right after `head` (the most-recently-used position).
            # Save `first_real` before overwriting `head.next` so we do not lose the rest of the list.
            first_real = self.head.next
            assert first_real is not None
            node.prev = self.head
            node.next = first_real
            self.head.next = node
            first_real.prev = node
    
        def get(self, key: int) -> int:
            # Use `is None` (never truthiness) because key 0 and value 0 are valid cache entries.
            node = self.key_to_node.get(key)
            if node is None:
                return -1
    
            # A cache hit counts as a fresh use: move `node` to the most-recently-used front.
            self._remove(node)
            self._insert_after_head(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            # Phase 1: If `key` is already cached, overwrite its value and promote it to the front.
            existing = self.key_to_node.get(key)
            if existing is not None:
                existing.value = value
                self._remove(existing)
                self._insert_after_head(existing)
                return
    
            # Phase 2: Adding a brand-new key when full — evict the least recently used node (`tail.prev`)
            # BEFORE inserting, keeping peak resident count <= capacity.
            if len(self.key_to_node) == self.capacity:
                lru_node = self.tail.prev
                assert lru_node is not None and lru_node is not self.head
                self._remove(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Phase 3: Create the new node, register it in the map, and place it at the front.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._insert_after_head(new_node)
    
    
    def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        cache = LRUCache(capacity)
        # results: records each operation's return value (int 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(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine keeping at most capacity reference books in a single stack on your desk: whenever you open a book (get) or add a new book (put), you place it right on top of the stack, and whenever the stack is full and a brand-new book arrives, you clear space by shelving the dusty book at the very bottom. That policy is an LRU (Least Recently Used) cache — a bounded key-value store that evicts whichever item has gone the longest without being read or written. To make both "grab any book instantly" and "move it to the top" run in O(1) time, we pair a hash map (a key-to-node lookup table with O(1) average access) with a doubly linked list (a chain of nodes with prev and next pointers so any node can be unlinked and moved to the front in O(1) pointer updates), capped at both ends by permanent sentinel (dummy) nodes head and tail so we never hit None-pointer special cases.

Why do single-structure solutions fall short? Keeping entries in a plain array or Python list makes moving a hit from the middle to the front shift up to capacity elements (O(capacity) per call, or 10^10 work across 100,000 operations). Conversely, storing (value, last_used_timestamp) in a plain dictionary makes get fast, but evicting the oldest key requires scanning all capacity entries (O(capacity)) or maintaining a lazy heap that accumulates stale entries.

Here is a tiny 5-step trace with capacity = 2:

1. put(10, 50) -> map={10},    list: head <-> [10:50] <-> tail
2. put(20, 60) -> map={10,20}, list: head <-> [20:60] <-> [10:50] <-> tail
3. get(10)     -> returns 50,  list: head <-> [10:50] <-> [20:60] <-> tail  (10 promoted to MRU!)
4. put(30, 70) -> full! evict tail.prev ([20:60]), insert [30:70] at front:
                  map={10,30}, list: head <-> [30:70] <-> [10:50] <-> tail
5. get(20)     -> key 20 not in map -> returns -1

Complexity

  • Time: O(1) average per get and put (O(n) total across n operations). Each operation performs at most one or two hash-map lookups/updates (O(1) average time) and rewires a constant number of prev/next pointers (4 assignments to insert, 2 to unlink).
  • Space: O(capacity) for the cache (plus O(n) for the returned results list). Because we evict before inserting when len(key_to_node) == capacity, the cache never holds more than capacity real Node objects and capacity dictionary entries (plus the 2 permanent sentinels).

Edge cases

  • capacity == 1: Overwriting the sole cached key keeps it alive; inserting any distinct key first unlinks that sole node (temporarily leaving head <-> tail) and then inserts the new node.
  • Overwriting an existing key when full: put(5, 99) when key 5 is already cached updates 5's value and promotes 5 to head.next without evicting any key.
  • Cache miss on get: Returns -1 immediately and leaves the recency list untouched.
  • Zero keys and zero values (key = 0, value = 0): Valid under 0 <= key and 0 <= value; testing node is None rather than if not node avoids treating 0 as missing.
  • get on an empty cache or empty operation list: get returns -1 cleanly when head.next is tail, and operations = [] returns [].

Common mistakes

  • Forgetting to promote a key on get: Treating get as read-only lets hot keys drift toward tail and get evicted prematurely (Example 1 fails immediately without get promotion).
  • Evicting on an overwrite, or forgetting to refresh recency on an overwrite: Updating an existing key does not increase the key count and must still move that key to the front.
  • Storing only value (and not key) inside Node: When evicting lru_node = self.tail.prev, you only have the node reference; without lru_node.key, you cannot delete its entry from key_to_node in O(1) time.
  • Corrupting pointers during _insert_after_head: Writing self.head.next = node before saving the old self.head.next orphans the entire rest of the list. Naming first_real = self.head.next up front prevents this completely.
  • Updating the list without updating key_to_node (or vice versa): Leaving an evicted key in the dictionary turns future misses into ghost hits and breaks len(key_to_node) == capacity.

Alternative approaches

  • collections.OrderedDict (Python standard library): Under the hood, OrderedDict is implemented in C as a hash table plus a doubly linked list with move_to_end(key) and popitem(last=False), giving the same O(1) bounds in ~15 lines. In interviews, however, building Node and the doubly linked list explicitly is almost always what the interviewer wants to see.

Follow-up questions

  • How can you make concurrent reads and writes safe across multiple threads without turning a single lock into a bottleneck? Because even get(key) mutates prev/next pointers in the doubly linked list, a reader-writer lock (a lock allowing concurrent readers when state is unchanged) offers no concurrency benefit — every get and put is a write! Start by wrapping get and put in a single mutex (mutual exclusion lock, threading.Lock()), which is necessary even in Python because a thread switch mid-_remove can corrupt list pointers. Under high multi-core contention, use lock striping (sharding): partition the cache into S independent sub-caches of capacity capacity / S routed by hash(key) % S, each protected by its own mutex so threads hitting different shards run in parallel (or adopt an approximate policy like CLOCK that flips an atomic reference bit on get instead of relinking pointers).
  • When access popularity varies sharply across keys, how does LFU eviction compare against LRU, and where does each policy struggle? LFU (Least Frequently Used) evicts the item with the lowest access count rather than the oldest timestamp, so it outperforms LRU when popularity is stable and skewed — especially during a one-time sequential scan of cold keys, which flushes an entire LRU cache ("cache pollution") while LFU protects frequently hit keys. However, pure LFU struggles when traffic patterns shift over time because formerly popular keys keep high historical counts forever ("frequency stagnation") unless counts are periodically decayed. Production caches often combine both signals (such as Window-TinyLFU) and pick the winner by replaying real production access traces to measure hit rate.
  • If the cache must warm-start its state after an unexpected process crash, how would you design durable persistence? First confirm whether persistence is worth the latency cost, since an in-memory cache can usually cold-start empty and repopulate from the primary database. If warm recovery is required to prevent a post-crash database stampede, periodically write an atomic snapshot of (key, value) pairs ordered from least recent to most recent (writing to a temp file and renaming atomically), and append every put between snapshots to an append-only write-ahead log (WAL) on disk with per-record checksums. On restart, replay the latest snapshot followed by valid WAL records; batching fsync (the OS call that flushes buffered disk writes to durable storage) every few milliseconds trades a tiny window of lost cache updates for low put latency, and skipping get logging avoids turning every memory read into disk I/O at the cost of approximate post-crash recency order.

Follow-up questions

Similar questions

More Balyasny interview questions

All 4 Balyasny questions →