Fixed-Capacity LRU Cache Simulation

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a bounded key-value store of maximum size capacity governed by Least Recently Used (LRU) eviction, executing a stream of "get" and "put" commands and collecting all "get" responses in chronological order.

def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:

The store begins completely empty. At index i, operations[i] is either "get" (paired with arguments[i] == [key]) or "put" (paired with arguments[i] == [key, value]):

  • "get" ([key]):
    • When key is currently cached, promote key to most recently used and record its stored value in the output list.
    • When key is absent, record -1 in the output list without inserting key or altering recency order.
  • "put" ([key, value]):
    • Produces no output entry.
    • When key is already cached, overwrite its stored value with value and promote key to most recently used; no entry is evicted.
    • When key is absent: if the store currently contains capacity entries, first discard whichever entry is least recently used, then insert (key, value) as most recently used.

Inserting a new key, overwriting an existing key, and hitting an existing key on "get" each count as using that key. Return a list[int] containing one result per "get" command.

Examples

Example 1

Input:
  capacity   = 2
  operations = ["put", "put", "get", "put", "get", "put", "get", "get"]
  arguments  = [[10, 100], [20, 200], [10], [30, 300], [20], [40, 400], [10], [30]]
Output: [100, -1, -1, 300]

After inserting 10 and 20, reading 10 returns 100 and promotes 10 ahead of 20. Inserting 30 evicts 20 (so get(20) returns -1); inserting 40 then evicts 10 (so get(10) returns -1), while get(30) returns 300.

Example 2

Input:
  capacity   = 2
  operations = ["put", "put", "put", "put", "get", "get", "get"]
  arguments  = [[4, 40], [8, 80], [4, 45], [9, 90], [4], [8], [9]]
Output: [45, -1, 90]

put(4, 45) updates key 4 in place without eviction and refreshes its recency, leaving 8 as least recently used so put(9, 90) evicts 8.

Example 3

Input:
  capacity   = 1
  operations = ["put", "get", "put", "get", "get"]
  arguments  = [[3, 0], [3], [7, 25], [3], [7]]
Output: [0, -1, 25]

Storing 0 under key 3 is a valid entry, so get(3) returns 0. Because capacity == 1, put(7, 25) evicts key 3 before inserting key 7.

Constraints

  • 1 <= capacity <= 3000
  • 1 <= len(operations) == len(arguments) <= 2 * 10^5
  • 0 <= key <= 10^4
  • 0 <= value <= 10^9
  • Target O(1) average time per command.

Step-by-step walkthrough

  1. Understand the cache rules

    We need to simulate a fixed-capacity Least Recently Used (LRU) cache across a list of "get" and "put" commands and return the results of all "get" commands in order:

    • get(key): If key is in the cache, mark key as most recently used and return its value (note that a stored value of 0 is a valid hit, not a miss!). If key is missing, return -1 and leave the cache untouched.
    • put(key, value):
      • If key is already in the cache, overwrite its value and mark key as most recently used. Nothing is evicted, even if the cache is full.
      • If key is not in the cache and the cache already holds capacity keys, evict the least recently used key first, then insert (key, value) as the most recently used key.
  2. Why a plain Python list is too slow

    A simple working prototype keeps a dictionary values[key] = value alongside a plain Python list order of keys from oldest to newest:

    • On a hit or update: call order.remove(key) and order.append(key).
    • On eviction: call order.pop(0) and delete that key from values.

    While easy to write, both order.remove(key) and order.pop(0) scan or shift elements across the array, costing O(capacity) time per operation. With 2 * 10^5 operations and capacity = 3,000, that reaches roughly 6 * 10^8 array shifts. To hit O(1) average time per operation, we need a structure that can jump to any key and pull it out of the middle of the recency line without shifting anything else.

  3. Key idea: pair a dictionary with a doubly linked list

    We combine two data structures so each covers the other's weakness:

    1. A hash map (key_to_node dict): maps key -> Node so we can locate any key's node in O(1) average time.
    2. A doubly linked list of Nodes: keeps cached entries in recency order from oldest (left) to newest (right). Because every node stores pointers to both its prev and next neighbors, unlinking a node from the middle and splicing it onto the right end rewires just a handful of pointers in O(1) time!
    key_to_node dict:     10 ────────┐             20 ────────┐
                                     v                        v
    Doubly linked list:  [head] <-> [10: 100] <─────────> [20: 200] <-> [tail]
                         dummy      least recently used   most recently used  dummy
    

    Two small design choices eliminate edge-case bugs:

    • Dummy sentinel nodes head and tail: They permanently cap both ends of the list and never hold user keys. Even when the cache is empty (head <-> tail), every real node always has a non-None prev and next neighbor!
    • Store key inside Node: When we evict head.next, reading lru_node.key tells us which key to delete from key_to_node in O(1) time.
  4. Code the node and pointer helpers

    Let's write the two O(1) linked-list building blocks:

    • _remove_node(node) bridges node.prev and node.next directly across node.
    • _add_to_most_recent(node) splices node right between tail.prev and tail.
    _remove_node(X):        [prev_node] <-> [X] <-> [next_node]
                         => [prev_node] <---------> [next_node]
    
    _add_to_most_recent(X): [prev_most_recent] <---------> [tail]
                         => [prev_most_recent] <-> [X] <-> [tail]
    
    class Node:
        # Doubly-linked-list node storing (key, value) plus prev/next neighbor pointers.
        # Storing `key` on the node lets us delete the evicted key from `key_to_node` in O(1).
        def __init__(self, key: int, value: int):
            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 each cached int key -> its live Node in the doubly linked list.
            self.key_to_node: Dict[int, Node] = {}
    
            # Dummy sentinel nodes frame all real entries so list ends are never None:
            # head <-> [least recent] <-> ... <-> [most recent] <-> tail
            self.head = Node(-1, -1)
            self.tail = Node(-1, -1)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _remove_node(self, node: Node) -> None:
            # Unlink `node` in O(1) by wiring its left and right neighbors directly together.
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _add_to_most_recent(self, node: Node) -> None:
            # Splice `node` right before `tail` so it becomes the most recently used entry.
            prev_most_recent = self.tail.prev
            prev_most_recent.next = node
            node.prev = prev_most_recent
            node.next = self.tail
            self.tail.prev = node
    
  5. Code `get` and `put`

    With _remove_node and _add_to_most_recent ready, "promoting a node to most recently used" is just _remove_node(node) followed by _add_to_most_recent(node):

    • get(key): Look up node = self.key_to_node.get(key). Check if node is None: (never if not node: or if not value:, because 0 is a valid value!). On a hit, promote node and return node.value.
    • put(key, value): Handle the three cases in strict order:
      1. Existing key: update existing_node.value = value, promote existing_node, and return immediately (no eviction!).
      2. Full cache on a new key: lru_node = self.head.next is the oldest entry; unlink it and delete lru_node.key from self.key_to_node.
      3. Insert new key: create new_node = Node(key, value), record it in self.key_to_node, and append it right before tail.
        def get(self, key: int) -> int:
            # Phase 1 (Lookup): Check `is None` explicitly because stored value `0` is a valid hit.
            node = self.key_to_node.get(key)
            if node is None:
                return -1
    
            # Phase 2 (Refresh recency): Move the hit node to the most-recent end before returning.
            self._remove_node(node)
            self._add_to_most_recent(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            # Case 1: Key already exists -> update value in place and mark most recent (never evict!).
            existing_node = self.key_to_node.get(key)
            if existing_node is not None:
                existing_node.value = value
                self._remove_node(existing_node)
                self._add_to_most_recent(existing_node)
                return
    
            # Case 2: New key and cache is at capacity -> evict least recently used node (`head.next`).
            if len(self.key_to_node) == self.capacity:
                lru_node = self.head.next
                self._remove_node(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Case 3: Insert the new key-value node at the most-recent end.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._add_to_most_recent(new_node)
    
  6. Code the runner and trace Example 1

    run_lru_cache instantiates a fresh LRUCache(capacity) inside the function (so separate calls never leak state into each other), loops over zip(operations, arguments), and collects every get return value.

    def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:
        # Create a fresh cache per call so independent runs never share state.
        cache = LRUCache(capacity)
        get_results: List[int] = []
    
        for op, args in zip(operations, arguments):
            if op == "get":
                key = args[0]
                get_results.append(cache.get(key))
            elif op == "put":
                key = args[0]
                value = args[1]
                cache.put(key, value)
            else:
                raise ValueError(f"unknown operation {op!r}")
    
        return get_results
    

    Let's trace Example 1 (capacity = 2, showing head <-> ... <-> tail from least recent to most recent):

    put(10, 100): head <-> [10:100] <-> tail                                 outputs: []
    put(20, 200): head <-> [10:100] <-> [20:200] <-> tail                    outputs: []
    get(10):      head <-> [20:200] <-> [10:100] <-> tail   (10 promoted!)   outputs: [100]
    put(30, 300): full! evict head.next ([20:200]), insert [30:300]
                  head <-> [10:100] <-> [30:300] <-> tail                    outputs: [100]
    get(20):      miss! list unchanged                                       outputs: [100, -1]
    put(40, 400): full! evict head.next ([10:100]), insert [40:400]
                  head <-> [30:300] <-> [40:400] <-> tail                    outputs: [100, -1]
    get(10):      miss!                                                      outputs: [100, -1, -1]
    get(30):      head <-> [40:400] <-> [30:300] <-> tail   (30 promoted!)   outputs: [100, -1, -1, 300]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        # Doubly-linked-list node storing (key, value) plus prev/next neighbor pointers.
        # Storing `key` on the node lets us delete the evicted key from `key_to_node` in O(1).
        def __init__(self, key: int, value: int):
            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 each cached int key -> its live Node in the doubly linked list.
            self.key_to_node: Dict[int, Node] = {}
    
            # Dummy sentinel nodes frame all real entries so list ends are never None:
            # head <-> [least recent] <-> ... <-> [most recent] <-> tail
            self.head = Node(-1, -1)
            self.tail = Node(-1, -1)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _remove_node(self, node: Node) -> None:
            # Unlink `node` in O(1) by wiring its left and right neighbors directly together.
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _add_to_most_recent(self, node: Node) -> None:
            # Splice `node` right before `tail` so it becomes the most recently used entry.
            prev_most_recent = self.tail.prev
            prev_most_recent.next = node
            node.prev = prev_most_recent
            node.next = self.tail
            self.tail.prev = node
    
        def get(self, key: int) -> int:
            # Phase 1 (Lookup): Check `is None` explicitly because stored value `0` is a valid hit.
            node = self.key_to_node.get(key)
            if node is None:
                return -1
    
            # Phase 2 (Refresh recency): Move the hit node to the most-recent end before returning.
            self._remove_node(node)
            self._add_to_most_recent(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            # Case 1: Key already exists -> update value in place and mark most recent (never evict!).
            existing_node = self.key_to_node.get(key)
            if existing_node is not None:
                existing_node.value = value
                self._remove_node(existing_node)
                self._add_to_most_recent(existing_node)
                return
    
            # Case 2: New key and cache is at capacity -> evict least recently used node (`head.next`).
            if len(self.key_to_node) == self.capacity:
                lru_node = self.head.next
                self._remove_node(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Case 3: Insert the new key-value node at the most-recent end.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._add_to_most_recent(new_node)
    
    
    def run_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:
        # Create a fresh cache per call so independent runs never share state.
        cache = LRUCache(capacity)
        get_results: List[int] = []
    
        for op, args in zip(operations, arguments):
            if op == "get":
                key = args[0]
                get_results.append(cache.get(key))
            elif op == "put":
                key = args[0]
                value = args[1]
                cache.put(key, value)
            else:
                raise ValueError(f"unknown operation {op!r}")
    
        return get_results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a narrow desk shelf that holds at most capacity folders. Whenever you read a folder (get hit) or file an updated/new folder (put), you slide that folder to the rightmost end of the shelf; when the shelf is full and a brand-new folder arrives, you evict (discard) whichever folder has drifted all the way to the leftmost end because it has gone untouched the longest (LRU, or Least Recently Used eviction). To do both operations instantaneously, we pair a dictionary (key_to_node, mapping each key to its folder in O(1) average time) with a doubly linked list (a chain of nodes where each node points to both its left prev and right next neighbor so any node can be pulled out and re-inserted in O(1) time), framed by two sentinel (dummy) nodes (head and tail, permanent placeholder nodes at both ends so we never hit None pointers on an empty or 1-item list).

Why do simpler single-structure designs fall short? A dictionary by itself looks up keys in O(1) time, but cannot tell which of 3,000 keys was used longest ago without scanning timestamps in O(capacity) time. Conversely, storing keys in a plain array keeps recency order, but pulling a hit key out of the middle (list.remove) or evicting from index 0 (list.pop(0)) shifts up to capacity elements on every call. Using a singly linked list also fails because unlinking a node requires editing its previous node's next pointer, which you cannot reach in O(1) time without a prev pointer.

Here is a quick trace of the first five commands from Example 1 (capacity = 2):

1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [10:100] <-> [20:200] <-> tail
3. get(10)      -> hit (100); move 10 to right -> head <-> [20:200] <-> [10:100] <-> tail
4. put(30, 300) -> full! evict head.next ([20:200]), add [30:300] -> head <-> [10:100] <-> [30:300] <-> tail
5. get(20)      -> not in key_to_node -> returns -1 (list unchanged)

Complexity

  • Time: O(1) average per operation, O(q) total for q = len(operations). Every get or put performs one or two average-O(1) dictionary operations (get, assignment, del) and rewires a constant number (4 to 8) of linked-list pointers.
  • Space: O(capacity + g), where g is the number of get operations. At any moment key_to_node and the doubly linked list store at most capacity live entries (plus 2 sentinel nodes), and get_results stores one integer per get.

Edge cases

  • capacity = 1: Updating the single cached key replaces its value without eviction, while inserting any different key evicts the sole entry first.
  • Stored value equal to 0 (Example 3): 0 is falsy in Python, so checking if node is None: ensures get returns 0 instead of treating it as a -1 miss.
  • put on an existing key when full (Example 2): Must overwrite the value and promote the key to most-recent without evicting head.next.
  • Missed get: Returns -1 without inserting the key or disturbing the recency order of existing keys.
  • All puts or all gets: All-put workloads return []; get calls on an empty cache all return -1.

Common mistakes

  • Checking capacity before checking whether key already exists in put: If the cache is full and put(key, new_val) updates an existing key, evicting first mistakenly deletes the oldest key and leaves the cache one slot under capacity.
  • Updating existing_node.value without moving it to the tail: An update counts as a "use"; leaving the node near head causes it to be evicted too early.
  • Forgetting del self.key_to_node[lru_node.key] on eviction: Unlinking lru_node from the list without deleting it from the dictionary leaks memory, inflates len(self.key_to_node), and causes stale cache hits!
  • Omitting key from Node: Without lru_node.key, finding which dictionary key points to head.next requires an O(capacity) scan of the dictionary.
  • Storing cache state in a module-level global: Causes keys from one test call to leak into the next call.

Alternative approaches

  • Python's collections.OrderedDict: Built in C on top of this exact hash-table + doubly-linked-list design. Calling cache.move_to_end(key) promotes a key in O(1) time and cache.popitem(last=False) evicts the oldest key in O(1) time. In production Python OrderedDict is ideal, though in coding interviews writing Node and pointer helpers explicitly is usually expected.
  • Hash map + min-heap of (timestamp, key): Increments a counter on each access and pushes (timestamp, key) onto a heap, skipping outdated timestamps on eviction. Each operation degrades from O(1) to O(log q) time and accumulates stale entries in memory.

Follow-up questions

  • How would you make this cache safe and scalable under concurrent multithreaded reads and writes? Because even a get hit mutates prev/next pointers in the linked list, a read-write lock cannot allow parallel gets safely; the simplest correct design wraps get and put in a single mutex (a mutual-exclusion lock allowing one thread at a time). Under high concurrency across many CPU cores, hash sharding (splitting the cache into S independent sub-caches of capacity capacity // S, chosen by hash(key) % S, each with its own mutex) reduces lock contention by a factor of S while approximating global LRU closely.
  • How could you add per-entry time-to-live (TTL) expiration while keeping lookups fast? A TTL (time-to-live) means each entry becomes invalid after a fixed duration even if the cache is not full: store an expire_at timestamp on each Node and treat get(key) as a miss (unlinking and deleting the node immediately) whenever now >= node.expire_at. If all entries share the same TTL duration, expiration order matches insertion order; if entries have arbitrary TTLs, combine lazy checks on get with either a background cleanup sweep or a min-heap keyed by expire_at so dead entries do not hog capacity forever.
  • What data-structure changes are needed to switch the eviction policy to Least Frequently Used (LFU) in O(1) time? LFU (Least Frequently Used) evicts the key with the lowest access count, breaking ties by least recently used. To keep O(1) time, maintain key_to_node, an integer min_freq, and a freq_to_list dictionary mapping each frequency f to its own doubly linked list of nodes: touching a key moves its node from freq_to_list[f] to the most-recent end of freq_to_list[f + 1] (incrementing min_freq if f == min_freq and freq_to_list[f] just became empty), while inserting a new key evicts the oldest node from freq_to_list[min_freq] and resets min_freq = 1.

Follow-up questions

Similar questions

More ByteDance interview questions

All 160 ByteDance questions →