In-Memory Cache With LRU Eviction

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a fixed-size key-value cache driven by lru_cache(capacity, operations, arguments) that evicts its least recently accessed entry whenever a new key must fit into a full store.

The cache starts empty with maximum slot count capacity and processes commands from parallel lists operations and arguments:

  • "get" with arguments[i] = [key]: Look up key. When key is currently cached, promote that entry to become the most recently accessed item and output its stored integer value. When key is absent, output -1 and leave the existing recency order unchanged.
  • "put" with arguments[i] = [key, value]: Associate key with value, promote key to become the most recently accessed item, and append None to the output list. Overwriting a key that is already cached updates its value in place without evicting any entry. Inserting a brand-new key when the cache already holds capacity keys first removes whichever cached key has gone the longest without a "get" hit or "put" write.

Return a list containing one result (int or None) per command in operations. Every "get" and "put" call must execute in O(1) amortized time.

Examples

Example 1

  • Input:
    • capacity = 2
    • operations = ["put", "put", "get", "put", "get", "put", "put", "get", "get", "get"]
    • arguments = [[10, 100], [20, 200], [10], [30, 300], [20], [10, 150], [40, 400], [30], [10], [40]]
  • Output: [None, None, 100, None, -1, None, None, -1, 150, 400]
  • Explanation:
    1. put(10, 100) and put(20, 200) fill both slots (20 is newest, 10 is oldest).
    2. get(10) returns 100 and promotes key 10, making key 20 the oldest entry.
    3. put(30, 300) needs space for a new key, so it evicts 20 and caches 30 -> 300.
    4. get(20) misses and returns -1.
    5. put(10, 150) updates key 10 in place without evicting 30, promoting 10 ahead of 30.
    6. put(40, 400) evicts the oldest key 30 and caches 40 -> 400.
    7. Subsequent lookups return -1 for 30, 150 for 10, and 400 for 40.

Example 2

  • Input:
    • capacity = 1
    • operations = ["get", "put", "get", "put", "get", "get"]
    • arguments = [[5], [5, 50], [5], [8, 80], [5], [8]]
  • Output: [-1, None, 50, None, -1, 80]
  • Explanation: Reading key 5 on an empty cache returns -1. After storing 5 -> 50 and reading 50, inserting 8 -> 80 into the single-slot cache evicts key 5, so get(5) returns -1 while get(8) returns 80.

Constraints

  • 1 <= capacity <= 3,000
  • 0 <= len(operations) == len(arguments) <= 100,000
  • Each operations[i] is either "get" (with arguments[i] = [key]) or "put" (with arguments[i] = [key, value]).
  • -10^5 <= key, value <= 10^5
  • Both "get" and "put" must run in O(1) amortized time.

Step-by-step walkthrough

  1. Understand the goal and the judge format

    We need to build an in-memory key-value cache with a fixed positive capacity and a least-recently-used (LRU) eviction rule:

    • get(key) looks up key. If it is missing, return -1 and leave the cache untouched. If it is present, return its value and mark key as the most recently used entry.
    • put(key, value) stores value under key. If key is already in the cache, overwrite its value and mark key as most recently used (no eviction happens because the number of stored keys did not grow). If key is brand-new and the cache already holds capacity items, first evict the least recently used entry — the one that has gone the longest without a get or put — and then insert the new entry as most recently used.

    Both get and put must run in amortized O(1) time (constant average work per call).

    The judge tests our class through lru_cache(capacity, operations, arguments): it creates one cache of size capacity, runs each operations[i] with arguments[i] ([key] for "get", [key, value] for "put"), and collects one output per operation (the integer result for "get", or None for "put").

  2. Why one data structure alone is too slow

    To make both operations O(1), we need to do three things in constant time:

    1. Find an entry by key.
    2. Move any existing entry to the "most recently used" front when it is read or updated.
    3. Drop the "least recently used" entry from the back when a full cache needs room.

    Neither a list nor a plain dictionary can do all three alone:

    • A plain list of [key, value] pairs keeps entries in order, so the oldest entry sits at one end. However, finding a key requires scanning the list, and removing an entry from the middle shifts every element after it — costing O(capacity) time per call.
    • A plain hash map (dict) finds any key in O(1) average time, but without linked pointers between entries you cannot pull an arbitrary middle item out and move it to the front in O(1) time using basic dictionary lookups alone.

    The solution is to pair both structures together: a dictionary key_to_node maps each key directly to its Node inside a doubly linked list ordered from most recently used to least recently used.

  3. Combine a dictionary with a doubly linked list and dummy sentinels

    Here is how the dictionary and the doubly linked list work together right after put(30, 300) in Example 1 (capacity = 2):

    key_to_node (dict)          Doubly linked recency list
    ------------------          --------------------------
                                [head]     (dummy sentinel, never evicted)
                                  ⇅
       30 ───────────────────►  [30 : 300] (most recently used = head.next)
                                  ⇅
       10 ───────────────────►  [10 : 100] (least recently used = tail.prev)
                                  ⇅
                                [tail]     (dummy sentinel, never evicted)
    

    Three small design choices eliminate edge-case bugs:

    1. Doubly linked (prev and next pointers): When key_to_node[key] hands us a node in the middle of the list, we need both node.prev and node.next to stitch its neighbors together in O(1). A singly linked list would force an O(capacity) search from the head just to find node.prev.
    2. Each Node stores both key and value: When the cache is full, we find the victim from the list (tail.prev), and we also need to delete that victim from key_to_node. Storing key on the node tells us which dictionary key to delete.
    3. Dummy sentinel head and tail nodes: Even when the cache holds zero items (head <-> tail), every real node we ever insert or remove sits strictly between head and tail. That guarantees node.prev and node.next are never None, so we never need if branches for an empty list or capacity 1.
    class Node:
        """One cache entry stored inside the doubly linked recency list."""
    
        def __init__(self, key: int, value: int):
            # Store key alongside value so evicting tail.prev knows 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: dict mapping int key -> Node currently inside the doubly linked list
            self.key_to_node: Dict[int, Node] = {}
    
            # Dummy sentinel nodes keep the list framed as:
            #   head <-> [most recent] <-> ... <-> [least recent] <-> tail
            # Because head and tail are never removed, real nodes always have non-None neighbors.
            self.head = Node(0, 0)
            self.tail = Node(0, 0)
            self.head.next = self.tail
            self.tail.prev = self.head
    
  4. Write the three O(1) list pointer helpers

    Every change to recency order reduces to two tiny pointer operations:

    • _unlink(node) detaches node from wherever it currently sits by connecting prev_node and next_node directly to each other.
    • _push_front(node) splices node right between self.head and old_first = self.head.next. Saving old_first in a local variable first makes the four pointer assignments impossible to mix up:
    Before _push_front(node):
      head  <──────────────>  old_first
    
    After _push_front(node):
      head  <──>  node  <──>  old_first
    

    Marking an existing node as most recently used (_move_to_front) simply calls _unlink(node) followed by _push_front(node).

        def _unlink(self, node: Node) -> None:
            # Bypass node by wiring its left and right neighbors directly to each other in O(1).
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _push_front(self, node: Node) -> None:
            # Insert node right after dummy head (the most-recently-used position).
            old_first = self.head.next
            node.prev = self.head
            node.next = old_first
            old_first.prev = node
            self.head.next = node
    
        def _move_to_front(self, node: Node) -> None:
            # Refreshing an entry's recency = detach from current spot + insert at front.
            self._unlink(node)
            self._push_front(node)
    
  5. Implement get and put without eviction traps

    Now get and put read like plain English, provided we watch out for two classic traps:

    1. In get(key), test if node is None: (never if not node.value:). A cached value of 0 (or even -1) is still a valid cache hit that must refresh recency and return the stored number.
    2. In put(key, value), check whether key already exists BEFORE checking capacity. Updating an existing key in a full cache keeps the entry count unchanged. If you checked len(self.key_to_node) == self.capacity first, updating an existing key in a full cache would mistakenly evict another key!
        def get(self, key: int) -> int:
            node = self.key_to_node.get(key)
            # Test `is None` explicitly so cached values like 0 or -1 still count as hits.
            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.key_to_node.get(key)
            if existing_node is not None:
                # Updating an existing key never increases cache size, so nothing is evicted.
                existing_node.value = value
                self._move_to_front(existing_node)
                return
    
            if len(self.key_to_node) == self.capacity:
                # Cache is full and key is new: evict the least-recently-used node right before tail.
                lru_node = self.tail.prev
                self._unlink(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Insert the brand-new entry into both the hash map and the front of the list.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._push_front(new_node)
    
  6. Replay the operations and trace Example 1

    Finally, lru_cache instantiates LRUCache(capacity) and loops through (op, args) pairs:

    def lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        cache = LRUCache(capacity)
        # results: one output per call (int value 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("unknown operation: " + op)
        return results
    

    Let's trace Example 1 (capacity = 2) from start to finish, showing the list from head (MRU) to tail (LRU) after each call:

    Call           Output  List state (head <-> MRU ... LRU <-> tail)
    -------------  ------  ------------------------------------------------
    put(10, 100)   None    head <-> [10:100] <-> tail
    put(20, 200)   None    head <-> [20:200] <-> [10:100] <-> tail
    get(10)        100     head <-> [10:100] <-> [20:200] <-> tail          (10 moves to front!)
    put(30, 300)   None    head <-> [30:300] <-> [10:100] <-> tail          (full: tail.prev [20:200] evicted)
    get(20)        -1      head <-> [30:300] <-> [10:100] <-> tail          (miss: list unchanged)
    put(10, 150)   None    head <-> [10:150] <-> [30:300] <-> tail          (update in place + move to front)
    put(40, 400)   None    head <-> [40:400] <-> [10:150] <-> tail          (full: tail.prev [30:300] evicted)
    get(30)        -1      head <-> [40:400] <-> [10:150] <-> tail          (miss: list unchanged)
    get(10)        150     head <-> [10:150] <-> [40:400] <-> tail          (10 moves to front)
    get(40)        400     head <-> [40:400] <-> [10:150] <-> tail          (40 moves to front)
    

    Collecting the outputs gives [None, None, 100, None, -1, None, None, -1, 150, 400]. Notice how both get(10) and put(10, 150) rescued key 10 by moving it ahead of the other cached key, causing 20 and then 30 to be evicted instead.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class Node:
        """One cache entry stored inside the doubly linked recency list."""
    
        def __init__(self, key: int, value: int):
            # Store key alongside value so evicting tail.prev knows 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: dict mapping int key -> Node currently inside the doubly linked list
            self.key_to_node: Dict[int, Node] = {}
    
            # Dummy sentinel nodes keep the list framed as:
            #   head <-> [most recent] <-> ... <-> [least recent] <-> tail
            # Because head and tail are never removed, real nodes always have non-None neighbors.
            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:
            # Bypass node by wiring its left and right neighbors directly to each other in O(1).
            prev_node = node.prev
            next_node = node.next
            prev_node.next = next_node
            next_node.prev = prev_node
    
        def _push_front(self, node: Node) -> None:
            # Insert node right after dummy head (the most-recently-used position).
            old_first = self.head.next
            node.prev = self.head
            node.next = old_first
            old_first.prev = node
            self.head.next = node
    
        def _move_to_front(self, node: Node) -> None:
            # Refreshing an entry's recency = detach from current spot + insert at front.
            self._unlink(node)
            self._push_front(node)
    
        def get(self, key: int) -> int:
            node = self.key_to_node.get(key)
            # Test `is None` explicitly so cached values like 0 or -1 still count as hits.
            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.key_to_node.get(key)
            if existing_node is not None:
                # Updating an existing key never increases cache size, so nothing is evicted.
                existing_node.value = value
                self._move_to_front(existing_node)
                return
    
            if len(self.key_to_node) == self.capacity:
                # Cache is full and key is new: evict the least-recently-used node right before tail.
                lru_node = self.tail.prev
                self._unlink(lru_node)
                del self.key_to_node[lru_node.key]
    
            # Insert the brand-new entry into both the hash map and the front of the list.
            new_node = Node(key, value)
            self.key_to_node[key] = new_node
            self._push_front(new_node)
    
    
    def lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        cache = LRUCache(capacity)
        # results: one output per call (int value 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("unknown operation: " + op)
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a narrow shelf on your desk that holds at most capacity reference books, paired with a card catalog right next to it. Whenever you look up a book (get) or place a book on the shelf (put), you slide that book into the leftmost spot so the books you touched most recently always sit near the left end. When the shelf is completely full and a brand-new book arrives, the book sitting at the rightmost end — the least recently used (LRU) one, meaning the item that has gone the longest without being read or updated — is pushed off the shelf to make room.

Why can't we use just a Python list or just a plain dictionary? A plain list keeps items in order, but finding a key or pulling an item out of the middle shifts all later elements and takes O(capacity) time per call. A plain hash map (dict, a key-value table that jumps straight to a key's bucket using its hash code) finds keys in O(1) average time, but gives you no way to pull an arbitrary middle item to the front in O(1) without linked pointers. By combining a dictionary (key -> Node) with a doubly linked list (a chain of nodes where each node points to both its left neighbor prev and right neighbor next), the dictionary jumps straight to any node in O(1) and the list rewires four neighbor pointers in O(1). We also cap the ends of the list with two sentinel nodes (permanent dummy head and tail nodes that hold no real data) so we never have to write special None checks for an empty cache or single-element edge cases.

Here is a tiny trace with capacity = 2 on the first five calls of Example 1 (put(10, 100), put(20, 200), get(10), put(30, 300), get(20)):

1. put(10, 100) -> head <-> [10:100] <-> tail
2. put(20, 200) -> head <-> [20:200] <-> [10:100] <-> tail      (20 is MRU, 10 is LRU)
3. get(10)->100 -> head <-> [10:100] <-> [20:200] <-> tail      (reading 10 moves it to MRU!)
4. put(30, 300) -> full! evict tail.prev ([20:200]), delete key 20 from dict,
                   insert [30:300] at front -> head <-> [30:300] <-> [10:100] <-> tail
5. get(20)-> -1 -> key 20 is no longer in dict -> cache miss (-1)

Complexity

Let C be capacity and M be the number of operations replayed by lru_cache.

  • Time: O(1) amortized per get and put (O(M) total across M operations). Amortized O(1) means that even though the underlying hash table occasionally resizes and copies its buckets, the total cost averaged over any sequence of operations is a constant number of steps per call: one or two O(1) dictionary lookups/updates plus at most six pointer assignments in _unlink and _push_front.
  • Space: O(C) for the cache (O(M) extra for the judge's output list). At any moment key_to_node holds at most C keys and the doubly linked list holds at most C real Node objects plus the two permanent dummy sentinels head and tail.

Edge cases

  • capacity = 1: Every new key immediately evicts the sole cached key, whereas updating or reading that same key keeps it cached without error because head and tail prevent neighbor pointers from ever becoming None.
  • Updating an existing key when the cache is already full: put updates the value in place and moves the node to the front without evicting anything, because the total number of keys stays equal to capacity.
  • get on an empty cache or missing key: Returns -1 immediately and leaves the recency order completely unchanged.
  • Cached value 0 or negative numbers (including -1): Checking if node is None: ensures a stored value of 0 returns 0 and refreshes recency. Note that with an API returning -1 on misses, a caller cannot tell a stored -1 apart from a miss externally, though internally our cache still tracks and refreshes that key properly.
  • Key 0: Even though self.head and self.tail are initialized as Node(0, 0), they are never inserted into self.key_to_node, so user key 0 never collides with the sentinels.

Common mistakes

  • Forgetting to move the node to the front on get: A cache read counts as a recent use. Leaving the list untouched turns LRU into FIFO (first-in, first-out) and evicts recently read keys too early.
  • Checking capacity before checking whether key already exists in put: If the cache has capacity = 2 with {10: 100, 20: 200} and put(10, 150) runs, checking fullness first wrongly evicts key 20 even though 10 was only being updated.
  • Forgetting del self.key_to_node[lru_node.key] on eviction: Unlinking tail.prev from the linked list alone leaves a stale reference in the dictionary, allowing get to keep returning evicted entries and letting memory grow without bound.
  • Overwriting self.head.next too early inside _push_front: If you write self.head.next = node before saving old_first = self.head.next, you lose your only pointer to the rest of the list and orphan every other cached entry.
  • Using a singly linked list or Python list: Removing a node from the middle of a singly linked list requires walking from head to find its predecessor in O(C) time, and list.pop(i) shifts elements in O(C) time.

Alternative approaches

  • Python's collections.OrderedDict: OrderedDict is implemented under the hood in C using this exact hash-table-plus-doubly-linked-list design. Calling move_to_end(key) refreshes recency in O(1) and popitem(last=False) evicts the oldest item in O(1). Mentioning OrderedDict in an interview shows practical Python knowledge, and then building Node + LRUCache by hand proves you understand the underlying data structure.
  • Plain list simulation (O(C) per operation): Maintain [key, value] pairs in a list from oldest to newest. It is too slow for large capacities, but because its logic is tiny and obviously right, it makes an ideal brute-force oracle for randomized testing.

Follow-up questions

  • How would you make this cache thread-safe under high concurrency without serializing every read behind a single global lock? A naive mutex (mutual-exclusion lock) around get and put works for low traffic, and a reader-writer lock (a lock allowing concurrent readers when no writer holds the lock) cannot parallelize get because even cache reads mutate doubly linked list pointers to move the hit node to the front. To scale across many CPU cores, split the keyspace into S independent shards (separate mini-caches of capacity C / S, selected via hash(key) % S), each guarded by its own lock; threads touching different shards run in parallel while maintaining high-quality approximate LRU eviction.
  • How would you extend the design so each entry also expires automatically after a per-item time-to-live (TTL)? Store an expires_at timestamp on each Node and first apply lazy expiration (checking now >= node.expires_at inside get and put, unlinking and deleting expired entries on sight in O(1)). Because unread expired nodes would otherwise occupy capacity until they drift to tail, pair lazy checks either with periodic background sampling or with a min-heap (a priority queue ordered by expires_at in O(log C) time) so put purges expired entries before evicting live ones; if every entry shares an identical TTL duration, a FIFO queue (first-in, first-out queue) replaces the heap in O(1).
  • What changes if the capacity limit is measured in total bytes rather than number of keys, where values have variable byte sizes? Record size_bytes on each Node and maintain a running used_bytes sum on the cache. Reject (or bypass caching for) any single item with size_bytes > capacity; otherwise update used_bytes on inserts and overwrites, then evict self.tail.prev inside a while used_bytes > capacity: loop. One large put can evict multiple small entries at once (O(C) worst-case for a single call), yet because every inserted node is evicted at most once over its lifetime, put still runs in amortized O(1) time.

Follow-up questions

Similar questions

More Microsoft interview questions

All 252 Microsoft questions →