Fixed-Capacity LRU Cache

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a bounded key-value store that evicts its least recently used (LRU) entry whenever space runs out, exposed through the batch runner lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]].

Create a single cache instance configured with maximum entry count capacity, execute each (operations[i], arguments[i]) pair in order, and record one output per step:

  • "get" with [key]:
    • If key is present in the cache, mark key as the most recently accessed entry and output its stored integer value.
    • If key is absent, output -1 and leave the cache contents and recency order untouched.
  • "put" with [key, value] (always outputs None):
    • If capacity <= 0, the cache cannot retain any items, so nothing is stored.
    • If key is already present, overwrite its value with value and mark key as most recently accessed without evicting any entry.
    • If key is new and the cache currently contains capacity items, evict the least recently accessed key—the cached key that has gone the longest without a successful "get" or "put"—before inserting (key, value) as most recently accessed.

Both "get" and "put" must run in O(1) average time.

Examples

Example 1

  • Input:
    • capacity = 2
    • operations = ["put", "put", "get", "put", "get", "get"]
    • arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [10]]
  • Output: [None, None, 100, None, -1, 100]
  • Explanation: After inserting 10 -> 100 and 20 -> 200, calling get(10) returns 100 and refreshes key 10, making key 20 the oldest untouched entry. Inserting 30 -> 300 into the full cache therefore evicts 20, so get(20) returns -1 while get(10) still returns 100.

Example 2

  • Input:
    • capacity = 2
    • operations = ["put", "put", "put", "put", "get", "get"]
    • arguments = [[4, 40], [5, 50], [4, 45], [6, 60], [5], [4]]
  • Output: [None, None, None, None, -1, 45]
  • Explanation: Writing put(4, 45) updates key 4 in place without evicting key 5, and promotes key 4 ahead of key 5. The subsequent put(6, 60) then evicts key 5, leaving keys 6 and 4 (45).

Example 3

  • Input:
    • capacity = 0
    • operations = ["put", "get"]
    • arguments = [[7, 70], [7]]
  • Output: [None, -1]
  • Explanation: Because capacity is 0, put(7, 70) stores nothing and get(7) misses with -1.

Constraints

  • 0 <= capacity <= 5 * 10^4
  • 0 <= len(operations) == len(arguments) <= 10^5
  • Each operations[i] is either "get" (with [key]) or "put" (with [key, value]).
  • -10^9 <= key, value <= 10^9
  • Target time complexity: O(1) average per operation (O(m) across m operations).
  • Target auxiliary cache space: O(max(0, capacity)).

Step-by-step walkthrough

  1. Restate the problem

    We need to build a bounded least-recently-used (LRU) cache holding up to capacity key-value pairs and supporting two operations in average O(1) time:

    • get(key) returns the integer stored under key, or -1 when key is absent. Every hit counts as an access, promoting key to most recently used.
    • put(key, value) stores value under key and marks key as most recently used. If key already exists, its value is updated in place without evicting any item. If key is brand new and the cache is already at capacity, we first evict the least recently used item (the one untouched longest).

    The batch function lru_cache(capacity, operations, arguments) runs all calls on one cache instance and returns one element per call: the integer result for get, and None for put. When capacity <= 0 (as in Example 3), the cache cannot store anything, so put is a no-op and every get returns -1.

  2. Why a single list or dictionary is not enough

    Suppose we start with the simplest possible design: a plain Python list of [key, value] pairs ordered from least recently used at index 0 to most recently used at the end.

    • On get(key), we scan the list to find key, pop it from the middle, and append it to the end.
    • On put(key, value), we scan to remove any old copy, append [key, value], and pop(0) if len > capacity.

    This brute force is easy to reason about, so it makes a great test oracle, yet both scanning for a key and popping from the front or middle shift up to capacity elements — costing O(capacity) per call instead of O(1).

    On the flip side, a plain Python dict finds key in average O(1) time, yet if we only store key -> value (even with a timestamp), evicting the oldest entry requires scanning the dictionary (O(capacity)) or maintaining a heap (O(log capacity)). Notice that we have two separate jobs:

    1. Jump directly to any key in O(1) time.
    2. Pull an item out of the middle, push it to the front, or drop the back item in O(1) time.
  3. Key idea: pair a hash map with a doubly linked list

    We get O(1) for both jobs by letting a hash map (dict) and a doubly linked list work together:

    • Doubly linked list in recency order: Every cache entry lives in a node with prev and next pointers to both neighbors. Because a node already knows its left and right neighbors, detaching it from the middle or inserting it at the front only updates a handful of pointers in O(1) time — zero shifting.
    • Hash map key -> Node: Instead of walking the list to find a key, self.nodes[key] jumps straight to that node in average O(1) time.
    • Store key inside Node too: When the cache is full, we find the victim at the back of the list (tail.prev). Storing key on that node tells us which entry to delete from self.nodes without searching the map.
    • Two dummy sentinel nodes (head and tail): We keep a permanent fake head at the front and fake tail at the back. Every real entry sits strictly between them, so node.prev and node.next are never None, eliminating empty-list and boundary if branches.
    Hash map (self.nodes):
      10 ──► [key=10, val=100]
      20 ──► [key=20, val=200]
    
    Doubly linked list (most recent on the left, least recent on the right):
      [head] ◄──► [key=20, val=200] ◄──► [key=10, val=100] ◄──► [tail]
                         ▲                       ▲
                   head.next (MRU)         tail.prev (LRU victim)
    
  4. Code the node and O(1) list helpers

    Every recency change boils down to two tiny pointer helpers:

    • _unlink(node) bridges node's left neighbor (prev_node) and right neighbor (next_node) directly to each other, lifting node out of the chain.
    • _push_front(node) splices node right between self.head and first_real = self.head.next. Saving first_real in a variable first makes the pointer assignments crystal clear and order-independent.
    _unlink(X):
      Before:  [prev_node] ◄──► [X] ◄──► [next_node]
      After:   [prev_node] ◄───────────► [next_node]
    
    _push_front(X):
      Before:  [head] ◄────────────────► [first_real]
      After:   [head] ◄──► [X] ◄───────► [first_real]
    
    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        def __init__(self, key: int, value: int):
            # Store `key` alongside `value` so when we evict `tail.prev` from the list,
            # we immediately know which key to delete from `self.nodes` in O(1) time.
            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
            # nodes: dict mapping key -> Node for O(1) average lookup, e.g. {10: Node(10, 100)}
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes permanently bookend the doubly linked list:
            # head <-> [most recently used ... least recently used] <-> tail
            self.head = Node(0, 0)
            self.tail = Node(0, 0)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _unlink(self, node: Node) -> None:
            # Detach `node` by connecting its left and right neighbors directly to each other.
            # Sentinels guarantee `node.prev` and `node.next` are never None for real entries.
            prev_node = node.prev
            next_node = node.next
            assert prev_node is not None and next_node is not None
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _push_front(self, node: Node) -> None:
            # Insert `node` right after `head`, marking it as the most recently used entry.
            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. Code get: promote on hit, leave untouched on miss

    When key is missing from self.nodes, we return -1 immediately — nothing is inserted and no other key's recency changes. When key is found, reading it counts as using it, so we _unlink its node and _push_front it before returning node.value.

        def get(self, key: int) -> int:
            # Cache miss: return -1 and leave recency order completely unchanged.
            if key not in self.nodes:
                return -1
    
            # Cache hit: promote the accessed node to the front before returning its value.
            node = self.nodes[key]
            self._unlink(node)
            self._push_front(node)
            return node.value
    
  6. Code put: check capacity, update, evict, then insert

    In put(key, value), checking the four phases in exact order avoids two subtle bugs:

    1. Non-positive capacity (capacity <= 0): Return right away. Without this guard, an empty cache with capacity = 0 satisfies len(self.nodes) == self.capacity (0 == 0), and self.tail.prev would try to unlink the head sentinel!
    2. Existing key (key in self.nodes): Update node.value, move node to the front, and return. Doing this before the capacity check guarantees that overwriting an existing key in a full cache never evicts another key (as in Example 2).
    3. Full cache (len(self.nodes) == self.capacity): Only reached for a brand-new key. Evict lru_node = self.tail.prev from both the linked list and self.nodes.
    4. Insert new key: Create Node(key, value), record it in self.nodes, and push it to the front.
        def put(self, key: int, value: int) -> None:
            # Phase 1: Guard capacity <= 0 first. Otherwise an empty cache has
            # len(self.nodes) == 0 == capacity and would try to evict the `head` sentinel.
            if self.capacity <= 0:
                return
    
            # Phase 2: Existing key — update in place and promote to most recent.
            # Checking this before eviction ensures an overwrite in a full cache evicts nothing.
            if key in self.nodes:
                node = self.nodes[key]
                node.value = value
                self._unlink(node)
                self._push_front(node)
                return
    
            # Phase 3: New key in a full cache — evict `tail.prev` (the least recently used node).
            if len(self.nodes) == self.capacity:
                lru_node = self.tail.prev
                assert lru_node is not None
                self._unlink(lru_node)
                del self.nodes[lru_node.key]
    
            # Phase 4: Insert the new entry into both the hash map and the front of the list.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._push_front(new_node)
    
  7. Walk through Example 1 and code the judge driver

    The driver lru_cache creates one LRUCache(capacity), loops over zip(operations, arguments), and appends either the return value of get or None for put.

    Let's trace Example 1 with capacity = 2:

    Call          Output  List (head <-> MRU ... LRU <-> tail)       Map keys
    put(10, 100)  None    head <-> (10:100) <-> tail                 {10}
    put(20, 200)  None    head <-> (20:200) <-> (10:100) <-> tail    {10, 20}
    get(10)       100     head <-> (10:100) <-> (20:200) <-> tail    {10, 20}  <- 10 promoted!
    put(30, 300)  None    head <-> (30:300) <-> (10:100) <-> tail    {10, 30}  <- tail.prev (20) evicted
    get(20)       -1      head <-> (30:300) <-> (10:100) <-> tail    {10, 30}  <- miss changes nothing
    get(10)       100     head <-> (10:100) <-> (30:300) <-> tail    {10, 30}
    

    Notice how get(10) on step 3 rescued key 10 by promoting it ahead of key 20, so put(30, 300) evicted key 20 instead. The collected outputs are [None, None, 100, None, -1, 100].

    def lru_cache(
        capacity: int,
        operations: List[str],
        arguments: List[List[int]],
    ) -> List[Optional[int]]:
        # Replay each operation on a single LRUCache instance and collect one output per call.
        cache = LRUCache(capacity)
        results: List[Optional[int]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "get":
                key = args[0]
                results.append(cache.get(key))
            elif operation == "put":
                key = args[0]
                value = args[1]
                cache.put(key, value)
                results.append(None)
            else:
                raise ValueError(f"unknown operation: {operation}")
    
        return results
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        def __init__(self, key: int, value: int):
            # Store `key` alongside `value` so when we evict `tail.prev` from the list,
            # we immediately know which key to delete from `self.nodes` in O(1) time.
            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
            # nodes: dict mapping key -> Node for O(1) average lookup, e.g. {10: Node(10, 100)}
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes permanently bookend the doubly linked list:
            # head <-> [most recently used ... least recently used] <-> tail
            self.head = Node(0, 0)
            self.tail = Node(0, 0)
            self.head.next = self.tail
            self.tail.prev = self.head
    
        def _unlink(self, node: Node) -> None:
            # Detach `node` by connecting its left and right neighbors directly to each other.
            # Sentinels guarantee `node.prev` and `node.next` are never None for real entries.
            prev_node = node.prev
            next_node = node.next
            assert prev_node is not None and next_node is not None
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _push_front(self, node: Node) -> None:
            # Insert `node` right after `head`, marking it as the most recently used entry.
            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:
            # Cache miss: return -1 and leave recency order completely unchanged.
            if key not in self.nodes:
                return -1
    
            # Cache hit: promote the accessed node to the front before returning its value.
            node = self.nodes[key]
            self._unlink(node)
            self._push_front(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            # Phase 1: Guard capacity <= 0 first. Otherwise an empty cache has
            # len(self.nodes) == 0 == capacity and would try to evict the `head` sentinel.
            if self.capacity <= 0:
                return
    
            # Phase 2: Existing key — update in place and promote to most recent.
            # Checking this before eviction ensures an overwrite in a full cache evicts nothing.
            if key in self.nodes:
                node = self.nodes[key]
                node.value = value
                self._unlink(node)
                self._push_front(node)
                return
    
            # Phase 3: New key in a full cache — evict `tail.prev` (the least recently used node).
            if len(self.nodes) == self.capacity:
                lru_node = self.tail.prev
                assert lru_node is not None
                self._unlink(lru_node)
                del self.nodes[lru_node.key]
    
            # Phase 4: Insert the new entry into both the hash map and the front of the list.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._push_front(new_node)
    
    
    def lru_cache(
        capacity: int,
        operations: List[str],
        arguments: List[List[int]],
    ) -> List[Optional[int]]:
        # Replay each operation on a single LRUCache instance and collect one output per call.
        cache = LRUCache(capacity)
        results: List[Optional[int]] = []
    
        for operation, args in zip(operations, arguments):
            if operation == "get":
                key = args[0]
                results.append(cache.get(key))
            elif operation == "put":
                key = args[0]
                value = args[1]
                cache.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 small desk shelf that holds at most capacity folders. Every time you read a folder (get) or place/update one (put), you slide that folder to the leftmost spot on the shelf. Folders you haven't touched in a while naturally drift toward the rightmost end, so when the shelf is full and a new folder arrives, the one at the far right is always the least recently used (LRU) entry and gets tossed out. To make both lookup and reordering instant even for 50,000 folders, we combine a hash map (a key-value lookup table such as Python's dict that finds any key in average O(1) time) with a doubly linked list (a chain of nodes where every node stores prev and next pointers to both of its neighbors), capped at both ends by two sentinel nodes (permanent dummy head and tail placeholder nodes that store no real data so every real node always has two valid neighbors).

Why do simpler single-structure designs fall short? Keeping entries in a plain Python list or collections.deque preserves recency order, yet finding or removing a key from the middle shifts neighboring items and costs O(capacity) time per call. Storing key -> (value, last_used_timestamp) in a plain dictionary makes reads and updates O(1), yet finding the smallest timestamp when evicting still requires scanning the whole dictionary in O(capacity) time (or O(log n) with a heap). By pointing each dictionary entry directly at its doubly linked list node, we jump to any node in average O(1) time and splice it out or move it to the front in worst-case O(1) pointer updates.

Here is Example 1 (capacity = 2) traced step by step:

1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [20:200] <-> [10:100] <-> tail
3. get(10)      -> returns 100, promotes 10 to front:
                   head <-> [10:100] <-> [20:200] <-> tail
4. put(30, 300) -> full (size 2 == capacity 2), evicts tail.prev ([20:200]):
                   head <-> [30:300] <-> [10:100] <-> tail
5. get(20)      -> key 20 is no longer in self.nodes -> returns -1
6. get(10)      -> returns 100, promotes 10 to front

Complexity

Let m be the number of operations and c be max(0, capacity).

  • Time: average O(1) per get and put, and O(m) total across the run. Each get or put performs at most two dictionary operations (in, lookup, insert, or del, each average O(1)) plus a constant number of pointer assignments in _unlink and _push_front (worst-case O(1)), never scanning the list.
  • Space: O(min(c, m)) for the cache (O(c) upper bound), plus O(m) for the judge's output list. The cache holds at most c real Node objects, c dictionary entries in self.nodes, and two fixed sentinel nodes (head and tail).

Edge cases

  • Zero or negative capacity (capacity <= 0): put returns immediately without storing anything, and every get returns -1 (Example 3).
  • Capacity 1: Every new key evicts the single stored key, whereas overwriting that same key updates its value without evicting anything.
  • Overwriting an existing key when full: put updates the value in place and moves the node to head.next without evicting tail.prev (Example 2).
  • Cache miss on get: Returns -1, does not insert the missing key, and leaves the recency order of existing keys untouched.
  • Zero values and negative keys: Stored values such as 0 and negative integer keys work normally because misses are checked via key not in self.nodes, not truthiness.
  • Empty operation list: Returns [] cleanly.

Common mistakes

  • Forgetting to promote on get: Treating get as a read-only lookup turns the cache into First-In-First-Out (FIFO) instead of LRU, evicting hot keys that were inserted early.
  • Evicting before checking key in self.nodes in put: If len(self.nodes) == self.capacity runs before if key in self.nodes, updating an existing key in a full cache wrongly deletes an innocent entry.
  • Omitting self.key on Node: When put evicts tail.prev, it has the Node object in hand, yet without lru_node.key it cannot delete the corresponding entry from self.nodes in O(1) time.
  • Skipping the capacity <= 0 guard: On an empty cache with capacity == 0, len(self.nodes) == self.capacity evaluates to 0 == 0, causing self.tail.prev to unlink self.head and corrupt the sentinels.
  • Using list or collections.deque for recency order: Removing an element from the middle of either structure takes O(c) time, quietly degrading get and put from O(1) to linear time.

Alternative approaches

  • Python's collections.OrderedDict: OrderedDict already pairs a hash table with a doubly linked list in C. Calling move_to_end(key) marks a key as most recent in O(1) and popitem(last=False) evicts the oldest key in O(1). Mention it as the idiomatic production choice in Python, then build Node + dict manually because interviewers ask this problem specifically to see pointer design.
  • Timestamps with a min-heap: Store a monotonically increasing counter on every access and push (timestamp, key) onto a min-heap (a binary tree stored in an array whose smallest element sits at index 0 and pops in O(log n) time), using lazy deletion (leaving outdated (timestamp, key) pairs in the heap and discarding them when they surface during eviction). This is slower (O(log n) per operation) and uses extra memory for stale heap entries until rebuilt.

Follow-up questions

  • How would you synchronize this cache for multi-threaded reads and writes without creating a single global bottleneck? Because get mutates pointers inside the doubly linked list to promote hits, concurrent reads still mutate shared state, so a reader-writer lock provides no advantage over a standard mutex (a mutual-exclusion lock such as threading.Lock allowing one thread inside get or put at a time). When a single lock becomes hot under heavy concurrency, use sharding (splitting keys across S independent sub-caches of capacity c / S selected by hash(key) % S, each guarded by its own lock), trading exact global LRU eviction for near-zero lock contention.
  • How can you extend each entry with a time-to-live (TTL) expiration window while keeping operations fast? Save an expires_at deadline on each Node when written. On get(key), check now >= node.expires_at; if expired, unlink the node, delete self.nodes[key], and return -1 — known as lazy expiry (reclaiming expired entries when touched rather than scheduling per-key timers). To prevent cold expired keys from occupying space forever, combine lazy expiry with either a lightweight background sweep or a secondary queue/min-heap ordered by expires_at.
  • What API change is needed if callers must be able to cache -1 as an ordinary integer value? Using -1 as the miss sentinel makes a miss indistinguishable from a hit whose cached payload happens to be -1. Widen the return contract of get to return Optional[int] (None on a miss), return a (found: bool, value: Optional[int]) pair, or raise KeyError on misses like Python's dict.

Follow-up questions

Similar questions

More Ambience Healthcare interview questions

All 1 Ambience Healthcare questions →