Least Recently Used (LRU) Cache

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a bounded Least Recently Used (LRU) key-value cache initialized with a positive integer capacity, evaluated through the driver function lru_cache_operations(capacity, operations, arguments).

The cache supports two operations, both running in O(1) average time:

  • get(key) -> int: Searches for key. On a hit, marks key as the most recently accessed entry and returns its associated value. On a miss, leaves recency order unchanged and returns -1.
  • put(key, value) -> None: Writes (key, value) and marks key as the most recently accessed entry. If key is already stored, its value is overwritten in place without evicting any entry. If key is absent and the cache already holds capacity entries, first evict whichever stored key has gone the longest without a get hit or put write.

Given capacity, a list operations of "put" and "get" strings, and a matching list arguments ([key, value] for "put", [key] for "get"), lru_cache_operations initializes one cache and returns a list recording None for each "put" and the integer result for each "get".

Examples

Example 1

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

Example 2

  • Input:
    • capacity = 2
    • operations = ["put", "put", "put", "get", "put", "get", "get"]
    • arguments = [[4, 40], [7, 70], [4, 45], [9], [8, 80], [7], [4]]
  • Output: [None, None, None, -1, None, -1, 45]
  • Explanation: put(4, 45) updates existing key 4 to 45 and refreshes its recency without evicting key 7. The missed get(9) returns -1 and does not disturb recency, so put(8, 80) evicts key 7, leaving keys 8 and 4 (45).

Constraints

  • 1 <= capacity <= 1000
  • key >= 0 and value >= 0 (non-negative integers)
  • 0 <= len(operations) == len(arguments) <= 2 * 10^5
  • Both get and put must run in O(1) average time

Step-by-step walkthrough

  1. Restate the problem and the eviction rules

    We want to build a Least Recently Used (LRU) cache of positive size capacity supporting two operations in O(1) average time:

    • get(key) -> int: If key is in the cache, mark it as most recently used and return its value; otherwise return -1 without changing anything.
    • put(key, value) -> None:
      • If key is already in the cache, update its value and mark it as most recently used (never evicting anything!).
      • If key is new and the cache is already at capacity, first evict the least recently used key, then insert (key, value) as the most recently used item.

    The judge tests our class through lru_cache_operations(capacity, operations, arguments), returning None for each "put" and the integer answer for each "get".

  2. Why a list or a dictionary alone cannot hit O(1)

    Suppose we kept entries in a plain Python list ordered from least to most recently used. Evicting the oldest item (pop(0)) or finding a key to move it to the back requires scanning and shifting up to capacity elements—O(capacity) per call instead of O(1).

    On the other hand, a plain dictionary gives O(1) key lookup, but a raw hash table gives no O(1) way to pull an arbitrary middle item out of a recency chain and splice it onto the front.

    To get O(1) for both lookup and reordering, we combine two data structures so each covers the other's weakness: - A dictionary nodes (key -> Node): jumps directly to any key's node in O(1) average time. - A doubly linked list of Node objects: keeps nodes ordered from Most Recently Used (MRU) at the front to Least Recently Used (LRU) at the back, letting us detach any node and re-attach it at the front in O(1) pointer updates.

  3. Visual blueprint: sentinel nodes and why each node stores its key

    Here is how nodes and the doubly linked list work together:

    Dictionary `nodes`:
       key 10 -------------------> +------------+
       key 20 ----+                | key = 10   | (LRU: oldest, next to be evicted)
                  |                | val = 100  |
                  v                +------------+
            +------------+               ^
            | key = 20   | (MRU)         |
            | val = 200  |               v
    +------+   +------------+       +------------+   +------+
    | head |<->| key=20,200 |<----->| key=10,100 |<->| tail |
    +------+   +------------+       +------------+   +------+
    (dummy)     (head.next)                          (dummy)
                  newest             (tail.prev)
                                       oldest
    

    Three small design choices keep the code clean and bug-free:

    1. Why doubly linked (prev and next)? When get(10) hits a node in the middle of the chain, we must stitch its left neighbor directly to its right neighbor. Storing node.prev gives us the left neighbor immediately in O(1) instead of walking from head in O(n).
    2. Why store key inside Node? When the cache is full, we find the eviction victim from the list (oldest = self.tail.prev), and we must also delete its entry from self.nodes via del self.nodes[oldest.key].
    3. Why permanent head and tail dummy sentinels? Initially head <-> tail. Because head and tail are never removed, every real node always sits strictly between two non-None nodes—so we never need if node.prev is None or if self.head is None branches!
  4. Code Node and the two pointer-rewiring helpers

    Every recency change boils down to two tiny O(1) pointer operations—_unlink(node) and _push_front(node):

    _unlink(node): bypass `node` by connecting `prev_node` <-> `next_node`
       Before:  [prev_node] <-> [node] <-> [next_node]
       After:   [prev_node] <------------> [next_node]
    
    _push_front(node): splice `node` right between `head` and `first = head.next`
       Before:  [head] <-----------------> [first]
       After:   [head] <-> [node] <------> [first]
    

    Saving prev_node, next_node, and first = self.head.next in local variables makes the pointer updates effortless to read and impossible to scramble:

    from typing import Dict, Optional
    
    
    class Node:
        def __init__(self, key: int, value: int):
            # Store `key` alongside `value` so when we evict `tail.prev`, we know 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
            # nodes: maps cached key -> its Node in the doubly linked list, e.g. {10: Node(10, 100)}.
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes permanently frame the list: head <-> [MRU ... LRU] <-> tail.
            # Real nodes always have non-None `prev` and `next`, avoiding empty/boundary special cases.
            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:
            # Phase: Detach `node` from its current spot by wiring its neighbors directly to each other.
            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:
            # Phase: Insert `node` right after `head` so `head.next` is always the most recently used item.
            first = self.head.next
            assert first is not None
            self.head.next = node
            node.prev = self.head
            node.next = first
            first.prev = node
    
  5. Code get, put, and the operation runner

    Watch two classic traps in get and put: - Test if node is None:, never if not node: or truthiness on value—because key = 0 and value = 0 are completely valid cached numbers! - In put, handle an existing key before checking len(self.nodes) == self.capacity: updating an already-cached key when the cache is full replaces its value in place and must not evict another key.

        def get(self, key: int) -> int:
            node = self.nodes.get(key)
            # Check `is None` explicitly because 0 is a valid cached value.
            if node is None:
                return -1
            # A cache hit counts as a fresh use: move `node` to the front (MRU position).
            self._unlink(node)
            self._push_front(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            node = self.nodes.get(key)
            if node is not None:
                # Phase 1 (update): Key is already cached -> update value, move to MRU, and NEVER evict.
                node.value = value
                self._unlink(node)
                self._push_front(node)
                return
    
            # Phase 2 (evict if full): Only a brand-new key on a full cache triggers eviction of `tail.prev` (LRU).
            if len(self.nodes) == self.capacity:
                oldest = self.tail.prev
                assert oldest is not None
                self._unlink(oldest)
                del self.nodes[oldest.key]
    
            # Phase 3 (insert): Create the new node, index it in the map, and place it at MRU.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._push_front(new_node)
    

    Finally, lru_cache_operations initializes one LRUCache(capacity) and replays the sequence of "put" and "get" calls:

    from typing import List, Optional
    
    
    def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        # Judge harness: initialize one LRUCache and replay all get/put operations.
        cache = LRUCache(capacity)
        results: List[Optional[int]] = []
        for op, args in zip(operations, arguments):
            if op == "put":
                cache.put(args[0], args[1])
                results.append(None)
            elif op == "get":
                results.append(cache.get(args[0]))
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    
  6. Trace Example 1 pointer-by-pointer

    Let's trace Example 1 (capacity = 2):

    Start:        nodes = {}              head <-> tail                              -> -
    put(10, 100): nodes = {10}            head <-> [10:100] <-> tail                 -> None
    put(20, 200): nodes = {10, 20}        head <-> [20:200] <-> [10:100] <-> tail    -> None
    get(10):      hit! move [10:100] MRU  head <-> [10:100] <-> [20:200] <-> tail    -> 100
    put(30, 300): full! evict tail.prev ([20:200]), delete key 20, push [30:300]:
                  nodes = {10, 30}        head <-> [30:300] <-> [10:100] <-> tail    -> None
    get(20):      key 20 not in `nodes`   head <-> [30:300] <-> [10:100] <-> tail    -> -1
    get(30):      hit! [30:300] at MRU    head <-> [30:300] <-> [10:100] <-> tail    -> 300
    

    Returned list: [None, None, 100, None, -1, 300].

  7. 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`, we know 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
            # nodes: maps cached key -> its Node in the doubly linked list, e.g. {10: Node(10, 100)}.
            self.nodes: Dict[int, Node] = {}
    
            # Dummy sentinel nodes permanently frame the list: head <-> [MRU ... LRU] <-> tail.
            # Real nodes always have non-None `prev` and `next`, avoiding empty/boundary special cases.
            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:
            # Phase: Detach `node` from its current spot by wiring its neighbors directly to each other.
            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:
            # Phase: Insert `node` right after `head` so `head.next` is always the most recently used item.
            first = self.head.next
            assert first is not None
            self.head.next = node
            node.prev = self.head
            node.next = first
            first.prev = node
    
        def get(self, key: int) -> int:
            node = self.nodes.get(key)
            # Check `is None` explicitly because 0 is a valid cached value.
            if node is None:
                return -1
            # A cache hit counts as a fresh use: move `node` to the front (MRU position).
            self._unlink(node)
            self._push_front(node)
            return node.value
    
        def put(self, key: int, value: int) -> None:
            node = self.nodes.get(key)
            if node is not None:
                # Phase 1 (update): Key is already cached -> update value, move to MRU, and NEVER evict.
                node.value = value
                self._unlink(node)
                self._push_front(node)
                return
    
            # Phase 2 (evict if full): Only a brand-new key on a full cache triggers eviction of `tail.prev` (LRU).
            if len(self.nodes) == self.capacity:
                oldest = self.tail.prev
                assert oldest is not None
                self._unlink(oldest)
                del self.nodes[oldest.key]
    
            # Phase 3 (insert): Create the new node, index it in the map, and place it at MRU.
            new_node = Node(key, value)
            self.nodes[key] = new_node
            self._push_front(new_node)
    
    
    def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        # Judge harness: initialize one LRUCache and replay all get/put operations.
        cache = LRUCache(capacity)
        results: List[Optional[int]] = []
        for op, args in zip(operations, arguments):
            if op == "put":
                cache.put(args[0], args[1])
                results.append(None)
            elif op == "get":
                results.append(cache.get(args[0]))
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

A Least Recently Used (LRU) cache works like a small stack of folders on your desk: whenever you read a folder (get) or update/add one (put), you place that folder right on top; when your desk runs out of room, you file away whichever folder has sunk all the way to the bottom because you haven't touched it in the longest time. To make both looking up any folder by name and moving it to the top take O(1) constant time, we pair a hash map (a key-value dictionary that jumps directly to any key in O(1) average time) with a doubly linked list (a chain of nodes where every node stores prev and next pointers to both neighbors, allowing O(1) removal from the middle and insertion at the front). Framing the list with two permanent sentinel nodes (head and tail dummy placeholders that are never evicted) ensures every real node always has two real neighbors, eliminating null-pointer edge cases.

Using either structure on its own falls short. Storing (key, value) pairs in a plain array or list makes finding a key or shifting items after removal take O(capacity) linear time per call. Conversely, a standalone hash table finds keys in O(1) time, but without doubly linked prev and next pointers there is no O(1) way to splice a freshly accessed key out of the middle of the recency order or jump straight to the oldest item on eviction.

Let's walk through Example 1 (capacity = 2): - put(10, 100) then put(20, 200): the list from newest to oldest is head <-> [20:200] <-> [10:100] <-> tail. - get(10): nodes[10] jumps straight to [10:100] in O(1), unlinks it, and pushes it after head, reordering the list to head <-> [10:100] <-> [20:200] <-> tail and returning 100. - put(30, 300): key 30 is new and len(nodes) == 2 == capacity, so we evict tail.prev ([20:200]), delete key 20 from nodes, and push [30:300] at the front: head <-> [30:300] <-> [10:100] <-> tail. - get(20) and get(30): key 20 is no longer in nodes (-1), while key 30 hits and returns 300.

Complexity

  • Time: O(1) average per get and put (O(n) total to replay n operations). Each call performs at most two O(1) average dictionary operations (get, assignment, or del) and rewires a fixed number (four) of linked-list pointers with zero loops.
  • Space: O(capacity), because the dictionary and doubly linked list store at most capacity Node objects at any moment (plus the two fixed head and tail sentinels).

Edge cases

  • Empty cache (get before any put): self.nodes.get(key) returns None and get immediately returns -1; head.next safely points to tail.
  • Capacity of 1: head.next and tail.prev point to the single cached node, and every new key cleanly evicts it before inserting.
  • Updating an existing key when full: put checks if node is not None: before checking len(self.nodes) == self.capacity, so updating an existing key never evicts another entry.
  • Updating an existing key refreshes its recency: put(4, 45) in Example 2 moves key 4 to head.next, making key 7 the next eviction victim.
  • Missed get leaves recency untouched: querying a missing key returns -1 without modifying any pointers.
  • Zero keys and zero values (put(0, 0)): testing if node is None: avoids treating 0 as falsy/missing.

Common mistakes

  • Evicting before checking whether key already exists: if a full cache evicts first on put(existing_key, new_val), it wrongly drops a valid key and shrinks below capacity.
  • Forgetting to move the node to the front on get or on put updates: without refreshing recency on hits and updates, the cache turns into FIFO (First-In, First-Out) instead of LRU.
  • Forgetting del self.nodes[oldest.key] during eviction (or omitting key from Node): unlinking tail.prev from the list without deleting its dictionary entry causes stale hits and unbounded memory growth.
  • Using a singly linked list: without node.prev, unlinking a middle node requires walking from head in O(capacity) time.

Alternative approaches

  • collections.OrderedDict: Python's standard-library OrderedDict implements this exact hash-map-plus-doubly-linked-list pattern in C via move_to_end(key) and popitem(last=False) in O(1) time. In an interview, mention OrderedDict as the production Python choice and then write the explicit Node implementation to demonstrate how it works under the hood.
  • Plain Python 3.7+ dict deletion + re-insertion: deleting and re-inserting a key moves it to the end while next(iter(d)) finds the oldest key, but repeated front deletions leave dead dummy slots at the start of CPython's internal entry table until a resize occurs, degrading next(iter(d)) away from steady O(1) on large caches.

Follow-up questions

  • How can you adapt this cache so multiple threads can call get and put safely without killing throughput? Because even get(key) mutates prev and next pointers to move the hit node to the front, a reader-writer lock does not allow concurrent reads—every hit is a write. The cleanest correct baseline wraps get and put in a single mutex (lock) (threading.Lock, ensuring only one thread modifies the map and list at a time). Under heavy multi-core contention, split the cache into S independent LRU shards indexed by hash(key) % S, each with capacity capacity / S and its own lock, or buffer read-hit recency updates in thread-local queues and apply them in batches to approximate LRU with near-lock-free reads.
  • How would you redesign the data structures to evict the Least Frequently Used (LFU) key in O(1) time instead? Least Frequently Used (LFU) evicts the key with the lowest access count, breaking ties by least recent use. To keep both get and put in O(1) time, store nodes: key -> Node(key, value, freq), a second map freq_lists: freq -> doubly linked list (each list ordered from MRU to LRU), and an integer min_freq. Whenever a key with frequency f is accessed, unlink it from freq_lists[f], increment min_freq to f + 1 if freq_lists[f] became empty and f == min_freq, and push the node to the front of freq_lists[f + 1]; on eviction, pop tail.prev from freq_lists[min_freq] (and reset min_freq = 1 when inserting a brand-new key).
  • When scaling to millions of cached keys, how can you reduce the per-entry memory overhead of doubly linked nodes? Every cached item allocates both a hash-table slot and a Node object carrying two 8-byte pointers (prev, next) plus object header metadata—in Python, adding __slots__ = ("key", "value", "prev", "next") eliminates each node's per-instance __dict__ and cuts node memory substantially, while in C++/Rust preallocating flat integer arrays prev[capacity] and next[capacity] replaces 8-byte pointers with 4-byte slot indices and improves CPU cache locality. If exact LRU ordering is not strictly required, the CLOCK (second-chance) algorithm (a circular buffer with a single 1-bit "recently used" flag per entry instead of two pointers) slashes metadata overhead to almost nothing. Finally, when cached values vary widely in byte size, cap total memory bytes rather than entry count so a handful of multi-megabyte values cannot trigger an out-of-memory crash.

Follow-up questions

Similar questions

More NVIDIA interview questions

All 208 NVIDIA questions →