Constant-Time LRU Cache with Fixed Capacity

Easy · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

High-throughput backend services routinely keep a bounded RAM cache ahead of slower persistent storage so repeated lookups avoid network and disk round-trips. Because fast memory is finite, caching introduces core engineering trade-offs between read speed, RAM footprint, staleness relative to the backing store, and per-request bookkeeping.

Design a bounded Least Recently Used (LRU) cache supporting constant-time reads and writes, and expose it through the driver function:

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

Instantiate a fresh cache of size capacity and execute operations[i] with arguments[i] for each step i:

  • "get" with [key]: Look up key in the cache. When present, promote key to be the most recently accessed entry and record its mapped integer in the output list. When absent, leave cache state untouched and record -1.
  • "put" with [key, value]: Store value under key and record None in the output list.
    • If key is already cached, overwrite its value in place and promote key to most recently accessed without removing any entry.
    • If key is new and the cache already holds capacity entries, first discard whichever cached entry has gone untouched for the longest time, then insert (key, value) as most recently accessed.

Every "get" and "put" step must execute in O(1) average time.

Examples

Example 1

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

Walk-through: - put(10, 50) and put(20, 80) fill both slots (20 is newest, 10 is oldest). - get(10) returns 50 and promotes key 10, making key 20 the oldest entry. - put(30, 90) exceeds capacity 2, so key 20 is evicted; a subsequent get(20) returns -1. - put(40, 70) evicts key 10 (now oldest), so get(10) returns -1 while get(40) returns 70.

Example 2

Input:
  capacity = 2
  operations = ["put", "put", "put", "put", "get", "get"]
  arguments = [[5, 100], [8, 200], [5, 150], [9, 300], [5], [8]]
Output:
  [None, None, None, None, 150, -1]

Walk-through: - After put(5, 100) and put(8, 200), key 5 is oldest. - put(5, 150) updates key 5 in place and refreshes its recency without evicting anything, leaving key 8 as oldest. - put(9, 300) therefore evicts key 8, so get(5) yields 150 and get(8) yields -1.

Constraints

  • 1 <= capacity <= 3000
  • 0 <= len(operations) == len(arguments) <= 2 * 10^5
  • Each operations[i] is either "get" (with [key]) or "put" (with [key, value]).
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5

Step-by-step walkthrough

  1. Restate the problem, caching trade-offs, and judge format

    In high-throughput backend services, placing an in-memory cache ahead of a slower persistent store turns millisecond disk or network reads into sub-microsecond RAM lookups. That speedup carries three practical trade-offs:

    • Memory bound & eviction: Fast RAM is limited, so once the cache reaches capacity keys, inserting a brand-new key must discard an existing one—here the Least Recently Used (LRU) key (the entry untouched for the longest time).
    • Bookkeeping overhead: Even a read (get) mutates internal recency state so the cache records that the key was just accessed.
    • Freshness / consistency: If another service modifies the backing database directly, cached values can drift out of date unless an invalidation or expiration policy is paired with the cache.

    We need an LRUCache(capacity) class where both get(key) and put(key, value) run in O(1) average time, wrapped by lru_cache_operations(capacity, operations, arguments) which replays "get" and "put" calls and returns [result_0, result_1, ...] (None for "put", mapped value or -1 for "get").

  2. Why a dictionary plus a plain list is too slow

    A natural first attempt keeps values = {} for O(1) key lookups and a Python list order = [...] of keys ordered from oldest to newest:

    • On a get(key) hit: call order.remove(key) and order.append(key).
    • On an eviction: call order.pop(0).

    That logic is completely accurate (and makes a great brute-force test oracle), but order.remove(key) scans and shifts elements in the list, and order.pop(0) shifts every remaining element left by one index. Each call costs O(capacity) time instead of O(1).

  3. Key idea: hash map pointing directly into a doubly linked list

    To get O(1) for both lookup and reordering, we combine two data structures so each covers the other's weakness:

    1. A hash map (self.nodes: dict[int, Node]) maps each key directly to its Node object in O(1) average time—no scanning required to find a node in the middle of the list.
    2. A doubly linked list (a chain of nodes where each node holds pointers prev and next to both neighbors) orders entries from most recently used (right after head) to least recently used (right before tail). Given a direct pointer to node, unlinking it from its two neighbors takes O(1) pointer assignments!
    Hash map (self.nodes):
       key 10 --------------------\
       key 30 ----\                \
                   v                v
    [head] <---> [30: 90] <---> [10: 50] <---> [tail]
                  ^MRU^          ^LRU^
             (most recent)   (evict next!)
    

    Notice one crucial detail: each Node stores both key and value. When the cache is full, we find the victim at self.tail.prev in O(1) time—and reading lru_node.key tells us which key to delete from self.nodes!

  4. Sentinel nodes and the two O(1) pointer helpers

    Empty lists and 1-element lists normally require messy if node.prev is None branches. Placing two permanent dummy sentinel nodes head and tail at the boundaries (head <-> tail when empty) guarantees every real cache node always sits strictly between two real neighbor objects!

    Every recency change in the entire cache reduces to two tiny O(1) helpers:

    _remove_node(node):
      Before:  [prev_node] <---> [node] <---> [next_node]
      After:   [prev_node] <----------------> [next_node]
    
    _add_after_head(node):
      Before:  [head] <----------------> [old_first]
      After:   [head] <---> [node] <---> [old_first]
    

    Saving prev_node, next_node, and old_first into named variables before changing any links makes the four pointer assignments impossible to tangle:

    class Node:
        """Doubly linked list node storing one cache entry (key, value) and neighbor pointers."""
    
        def __init__(self, key: int, value: int):
            # We store `key` alongside `value` so evicting tail.prev lets us delete `nodes[key]` in O(1).
            self.key = key
            self.value = value
            self.prev: Optional["Node"] = None
            self.next: Optional["Node"] = None
    
    
    class LRUCache:
        """Fixed-capacity Least Recently Used cache supporting O(1) average get and put.
        - nodes: dict mapping key -> Node for O(1) lookup.
        - head <-> ... <-> tail: doubly linked list ordered from most recent (after head)
          to least recent (before tail).
        """
    
        def __init__(self, capacity: int):
            self.capacity = capacity
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes bound both ends of the list: head <-> tail when empty.
            # Every real node always sits between two non-None nodes, avoiding edge-case checks.
            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` from its current position in the doubly linked list in O(1)."""
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _add_after_head(self, node: Node) -> None:
            """Insert `node` immediately after `head` (marking it most recently used) in O(1)."""
            # Save old_first before rewiring so pointer assignment order cannot lose the rest of the list.
            old_first = self.head.next
            self.head.next = node
            node.prev = self.head
            node.next = old_first
            old_first.prev = node
    
        def _move_to_front(self, node: Node) -> None:
            """Refresh an existing node's recency by moving it right after `head`."""
            self._remove_node(node)
            self._add_after_head(node)
    
  5. Implement `get`: lookup and refresh recency

    On get(key):

    • If key is not in self.nodes, return -1 without modifying anything.
    • If key is present, move its node right after head (because reading counts as using!) and return node.value.

    Always check if node is None rather than falsiness (if not val): 0 is a valid value (0 <= value <= 10^5) and must return 0, not -1!

        def get(self, key: int) -> int:
            # Check `is None` explicitly because stored value 0 is valid and must not be treated as missing.
            node = self.nodes.get(key)
            if node is None:
                return -1
            self._move_to_front(node)
            return node.value
    
  6. Implement `put`: in-place update vs eviction + insert

    put(key, value) has two distinct paths:

    1. Key already exists: Update existing_node.value = value, call _move_to_front(existing_node), and return immediately. Because no new key was added, we never evict on an update—even if len(self.nodes) == self.capacity.
    2. Key is brand new: If len(self.nodes) == self.capacity, first evict lru_node = self.tail.prev by unlinking it from the list and deleting self.nodes[lru_node.key]. Evicting before inserting ensures capacity = 1 cleanly empties the lone slot before adding the new node. Then create new_node, store it in self.nodes[key], and add it right after head.
        def put(self, key: int, value: int) -> None:
            existing_node = self.nodes.get(key)
            if existing_node is not None:
                # Phase 1 (update): overwrite value and refresh recency; key count does not grow, so no eviction.
                existing_node.value = value
                self._move_to_front(existing_node)
                return
    
            # Phase 2 (evict if full): evict BEFORE inserting so capacity = 1 works cleanly.
            if len(self.nodes) == self.capacity:
                lru_node = self.tail.prev
                self._remove_node(lru_node)
                del self.nodes[lru_node.key]
    
            # Phase 3 (insert): record new node in the map and place it at the most-recent front.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._add_after_head(new_node)
    
  7. Wire up the driver and trace Example 1

    lru_cache_operations instantiates LRUCache(capacity) and steps through (op, args) pairs. Let's trace Example 1 with capacity = 2:

    Start:        head <-> tail                                nodes={}               out=[]
    put(10, 50):  head <-> [10:50] <-> tail                    nodes={10}             -> None
    put(20, 80):  head <-> [20:80] <-> [10:50] <-> tail        nodes={10, 20}         -> None
    get(10):      head <-> [10:50] <-> [20:80] <-> tail        (10 moves to front!)   -> 50
    put(30, 90):  full! evict tail.prev = [20:80], del nodes[20]
                  head <-> [30:90] <-> [10:50] <-> tail        nodes={10, 30}         -> None
    get(20):      miss! list unchanged                         nodes={10, 30}         -> -1
    put(40, 70):  full! evict tail.prev = [10:50], del nodes[10]
                  head <-> [40:70] <-> [30:90] <-> tail        nodes={30, 40}         -> None
    get(10):      miss!                                                               -> -1
    get(40):      head <-> [40:70] <-> [30:90] <-> tail        (40 stays at front!)   -> 70
    

    Collected output: [None, None, 50, None, -1, None, -1, 70], matching Example 1!

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        """Doubly linked list node storing one cache entry (key, value) and neighbor pointers."""
    
        def __init__(self, key: int, value: int):
            # We store `key` alongside `value` so evicting tail.prev lets us delete `nodes[key]` in O(1).
            self.key = key
            self.value = value
            self.prev: Optional["Node"] = None
            self.next: Optional["Node"] = None
    
    
    class LRUCache:
        """Fixed-capacity Least Recently Used cache supporting O(1) average get and put.
        - nodes: dict mapping key -> Node for O(1) lookup.
        - head <-> ... <-> tail: doubly linked list ordered from most recent (after head)
          to least recent (before tail).
        """
    
        def __init__(self, capacity: int):
            self.capacity = capacity
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes bound both ends of the list: head <-> tail when empty.
            # Every real node always sits between two non-None nodes, avoiding edge-case checks.
            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` from its current position in the doubly linked list in O(1)."""
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _add_after_head(self, node: Node) -> None:
            """Insert `node` immediately after `head` (marking it most recently used) in O(1)."""
            # Save old_first before rewiring so pointer assignment order cannot lose the rest of the list.
            old_first = self.head.next
            self.head.next = node
            node.prev = self.head
            node.next = old_first
            old_first.prev = node
    
        def _move_to_front(self, node: Node) -> None:
            """Refresh an existing node's recency by moving it right after `head`."""
            self._remove_node(node)
            self._add_after_head(node)
    
        def get(self, key: int) -> int:
            # Check `is None` explicitly because stored value 0 is valid and must not be treated as missing.
            node = self.nodes.get(key)
            if node is None:
                return -1
            self._move_to_front(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            existing_node = self.nodes.get(key)
            if existing_node is not None:
                # Phase 1 (update): overwrite value and refresh recency; key count does not grow, so no eviction.
                existing_node.value = value
                self._move_to_front(existing_node)
                return
    
            # Phase 2 (evict if full): evict BEFORE inserting so capacity = 1 works cleanly.
            if len(self.nodes) == self.capacity:
                lru_node = self.tail.prev
                self._remove_node(lru_node)
                del self.nodes[lru_node.key]
    
            # Phase 3 (insert): record new node in the map and place it at the most-recent front.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._add_after_head(new_node)
    
    
    def lru_cache_operations(
        capacity: int,
        operations: List[str],
        arguments: List[List[int]],
    ) -> List[Optional[int]]:
        """Replay a sequence of get/put operations against LRUCache and collect return values."""
        cache = LRUCache(capacity)
        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 a small stack of at most capacity reference folders on your desk so you don't have to walk down to a slow basement archive (a disk database or remote storage service). Every time you read a folder (get) or add/update one (put), you place that folder right on top of the stack; when the desk is full and a brand-new folder arrives, you discard the folder sitting on the very bottom—the Least Recently Used (LRU) item. To both locate any folder instantly and pull a folder out of the middle of the stack without shuffling the others, we combine a hash map (a key-value lookup table with O(1) average access) that points directly to each folder with a doubly linked list (a chain of nodes where every node points to both its prev and next neighbor).

A naive design that tracks key order in a plain Python list has to search and shift elements whenever a key moves to the front (list.remove) or gets evicted (list.pop(0)), costing O(capacity) time per operation. Alternatively, storing last-used timestamps in a dictionary makes updates O(1), but finding the minimum timestamp during eviction still scans all capacity entries. Pairing nodes[key] -> Node with dummy sentinel nodes (head and tail boundary markers that never hold real data so every real node always has two non-None neighbors) makes every step constant-time.

Let's trace capacity = 2 on the first four calls of Example 1:

  1. put(10, 50): list becomes head <-> [10:50] <-> tail, nodes = {10: [10:50]}.
  2. put(20, 80): [20:80] goes right after head, giving head <-> [20:80] <-> [10:50] <-> tail.
  3. get(10): nodes[10] jumps directly to [10:50], unlinks it, and reinserts it after head, giving head <-> [10:50] <-> [20:80] <-> tail and returning 50.
  4. put(30, 90): cache is full (len(nodes) == 2), so we evict tail.prev ([20:80]), delete key 20 from nodes, and insert [30:90] after head, leaving head <-> [30:90] <-> [10:50] <-> tail.

Complexity

  • Time: O(1) average per get and put (O(q) total for q operations). Each get performs one hash-map lookup (O(1) average) and at most six pointer reassignments to unlink a node and reinsert it after head. Each put performs one hash-map lookup, at most one hash-map deletion + insertion (O(1) average), and constant-time pointer updates at tail.prev and head.next.
  • Space: O(capacity) for the cache (O(q) for the driver's output list). Because we evict whenever a new key would push len(self.nodes) past capacity, the hash map and doubly linked list hold at most capacity entries (plus 2 fixed sentinel nodes) at all times.

Edge cases

  • capacity = 1: Every new key immediately evicts the lone existing key (tail.prev, which is also head.next) before inserting the new node; updating the same key overwrites its value in place without evicting.
  • Updating an existing key when the cache is full: put hits the existing_node is not None branch first, refreshes its value and recency, and returns without evicting anything.
  • get on a missing key: Returns -1 immediately without inserting a placeholder or disturbing the recency order of existing keys.
  • Key 0 or value 0: Both 0 key and 0 value are valid under the constraints (0 <= key, 0 <= value). Checking if node is None avoids falsy-value bugs like return cache_dict.get(key) or -1.
  • Sequential scan larger than capacity: Inserting 10,000 distinct keys into a cache of capacity 3,000 evicts each older key in FIFO order, keeping only the latest 3,000 keys and bounding memory strictly to 3,000 nodes.

Common mistakes

  • Forgetting to move a key to the front on get: Reading a key counts as using it; leaving it near tail causes a frequently read key to be evicted prematurely.
  • Evicting when put updates an existing key: Checking if len(self.nodes) == self.capacity before checking if key in self.nodes wrongly deletes the oldest key when updating an existing key in a full cache.
  • Storing only value (and not key) inside Node: When evicting lru_node = self.tail.prev, you need lru_node.key to run del self.nodes[lru_node.key] in O(1) time. Forgetting del self.nodes[...] leaks memory, serves stale evicted keys on future gets, and stops len(self.nodes) == self.capacity from ever triggering again!
  • Using a singly linked list: Even with a hash map pointing directly to node, unlinking node requires updating node.prev.next, which takes O(capacity) to find in a singly linked list.
  • Overwriting self.head.next before reading it in _add_after_head: Saving old_first = self.head.next first avoids severing the rest of the list.

Alternative approaches

  • collections.OrderedDict (O(1) average time, O(capacity) space): Python's standard OrderedDict already pairs a hash table with an internal doubly linked list: move_to_end(key) refreshes recency in O(1) and popitem(last=False) evicts the oldest entry in O(1). It is idiomatic in production Python, though interviewers almost always ask you to build Node + LRUCache directly to test pointer manipulation.

Follow-up questions

  • How can you make concurrent reads and writes thread-safe without turning a single global lock into a throughput bottleneck? Because get mutates the doubly linked list on every cache hit, a reader-writer lock (a lock allowing multiple concurrent readers when state is unchanged) does not help—every hit behaves like a write! Wrapping the whole cache in a single mutex (a mutual-exclusion lock allowing only one thread at a time) is thread-safe but serializes all threads under heavy load. To cut contention dramatically, use sharding (also called lock striping: splitting the cache into S independent sub-caches of capacity capacity / S selected by hash(key) % S, each with its own mutex and doubly linked list), or buffer read-recency updates in lock-free ring buffers and drain them in batches, as high-throughput caches like Caffeine do.
  • When external services write directly to the backing database, what invalidation or expiration strategy keeps cached entries from staying stale? Write-through (updating both cache and database synchronously on writes) and write-around (writing straight to the database and bypassing or evicting from the local cache) only see writes performed by this service—writes made directly to the database by other services still leave our cache stale! Therefore, you must combine a TTL (Time-To-Live) expiration (an upper time limit after which cached entries automatically expire, bounding maximum staleness) with event-driven invalidation via change-data-capture (CDC) (streaming committed database row changes over a message bus like Kafka so cache instances immediately delete modified keys). For strict invariants where even millisecond staleness is unsafe, bypass the cache or validate a row version number against the primary store.
  • What changes if you replace LRU with LFU (Least Frequently Used), and what are the memory and workload trade-offs between frequency and recency? LFU (Least Frequently Used) evicts the key with the lowest access count (breaking ties by LRU), which protects hot keys when a large one-time batch scan sweeps through the cache—a workload that causes cache pollution in LRU (evicting genuinely popular keys to make room for scan items that are never read again). However, pure LFU suffers from "frequency hangover": a key accessed thousands of times yesterday can stay stuck in the cache long after nobody needs it unless counts periodically decay, and O(1) LFU requires noticeably heavier bookkeeping (a map from key to node, a map from each frequency count to its own doubly linked list, and a min_freq tracker). LRU uses half the metadata and adapts immediately when the working set shifts.

Follow-up questions

Similar questions

More Goldman Sachs interview questions

All 35 Goldman Sachs questions →