← Back to Algorithms, page 3

algorithms-0042 · Hard senior

Design an LRU cache with O(1) get and put, evicting the least recently used key when the cache is full.

Combine a hash map from key to node with a doubly linked list ordered by recency. get moves the node to the front; put inserts at the front and, when full, removes the node at the back. Both operations are O(1) because the map finds the node and the doubly linked list removes it without a scan. In Python, OrderedDict with move_to_end gives the same behaviour.

Full answer

Problem

Implement LRUCache(capacity) with:

  • get(key): return the value, or -1 if absent; mark the key as most recently used.
  • put(key, value): insert or update; if this adds a key beyond capacity, evict the least recently used key first.

Both must be O(1) average time.

Example: capacity 2: put(1, 1), put(2, 2), get(1) returns 1, put(3, 3) evicts key 2, get(2) returns -1.

Constraints: capacity >= 1 (0 raises ValueError), up to 2 x 10^5 calls.

Brute force

Store (key, value) in a list ordered by use: lookups and moves are O(n). Storing a timestamp per key in a dict makes get O(1) but eviction needs a scan for the oldest, O(n).

Optimal approach

  • map: key to node.
  • Doubly linked list with two sentinel nodes, head and tail; head.next is the most recent, tail.prev the least recent.
  • get: look up the node; if found, unlink it and re-insert after head.
  • put: if the key exists, update its value and move it to the front. Otherwise, if full, unlink tail.prev and delete its key from the map; then add a new node at the front.

Each node stores its key so eviction can delete the map entry.

Why it works

The list order is always the recency order: every access moves the accessed node to the front, so the back node is the least recently used. The map gives direct access to any node, and a doubly linked list can unlink a known node in O(1) by joining its neighbours. Sentinels remove the special cases for empty lists and end nodes.

Complexity

O(1) average time for get and put. O(capacity) space.

Code

python
class Node:
    __slots__ = ("key", "value", "prev", "next")

    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


class LRUCache:
    """get and put in O(1): hash map for lookup + doubly linked list for recency."""

    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.map = {}
        self.head, self.tail = Node(), Node()      # sentinels: head.next is most recent
        self.head.next, self.tail.prev = self.tail, self.head

    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev

    def _add_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._remove(node)
        self._add_front(node)                      # now most recently used
        return node.value

    def put(self, key, value):
        node = self.map.get(key)
        if node:
            node.value = value
            self._remove(node)
            self._add_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev                   # least recently used
            self._remove(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)


if __name__ == "__main__":
    c = LRUCache(2)
    c.put(1, 1)
    c.put(2, 2)
    assert c.get(1) == 1          # order now: 1, 2
    c.put(3, 3)                   # evicts 2
    assert c.get(2) == -1
    c.put(4, 4)                   # evicts 1
    assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
    c.put(4, 40)                  # update keeps size
    assert c.get(4) == 40 and len(c.map) == 2
    one = LRUCache(1)
    one.put("a", 1)
    one.put("b", 2)
    assert one.get("a") == -1 and one.get("b") == 2
    try:
        LRUCache(0)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Save as a42_lru_cache.py and run python3 a42_lru_cache.py. It prints all tests passed (Python 3.13.5).

Edge cases

Capacity 1 (every new key evicts the previous one). Updating an existing key must not evict anything and must refresh its recency. get on a missing key returns -1 without changing order. Capacity 0 is rejected. Thread safety: concurrent callers need a lock around each operation.

Pattern

Hash map plus doubly linked list: a composite structure where each part covers the other's weakness. Python's functools.lru_cache and collections.OrderedDict provide the same behaviour in production code. Related designs: LFU cache (frequency buckets) and time-based expiry.

python
class Node:
    __slots__ = ("key", "value", "prev", "next")

    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


class LRUCache:
    """get and put in O(1): hash map for lookup + doubly linked list for recency."""

    def __init__(self, capacity):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.map = {}
        self.head, self.tail = Node(), Node()      # sentinels: head.next is most recent
        self.head.next, self.tail.prev = self.tail, self.head

    def _remove(self, node):
        node.prev.next, node.next.prev = node.next, node.prev

    def _add_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node

    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return -1
        self._remove(node)
        self._add_front(node)                      # now most recently used
        return node.value

    def put(self, key, value):
        node = self.map.get(key)
        if node:
            node.value = value
            self._remove(node)
            self._add_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev                   # least recently used
            self._remove(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._add_front(node)


if __name__ == "__main__":
    c = LRUCache(2)
    c.put(1, 1)
    c.put(2, 2)
    assert c.get(1) == 1          # order now: 1, 2
    c.put(3, 3)                   # evicts 2
    assert c.get(2) == -1
    c.put(4, 4)                   # evicts 1
    assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
    c.put(4, 40)                  # update keeps size
    assert c.get(4) == 40 and len(c.map) == 2
    one = LRUCache(1)
    one.put("a", 1)
    one.put("b", 2)
    assert one.get("a") == -1 and one.get("b") == 2
    try:
        LRUCache(0)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Dict plus doubly linked list with head and tail sentinels; nodes store their key for eviction.

Complexity

Time: O(1) average for get and put. Space: O(capacity). OrderedDict.move_to_end and popitem(last=False) give the same O(1) behaviour.

By level

Fresher: Explains the hash map and linked list combination and walks through the example sequence. Should explain what least recently used means with an example.

Mid: Implements the design with sentinels, handles updates and capacity 1, and mentions OrderedDict. Tests capacity 1 and updates to an existing key.

Senior: Extends to LFU and TTL, discusses locking or sharded caches for concurrency and approximated LRU in systems such as Redis. Can explain why the node must store its key.

Key points

  • Hash map finds the node in O(1)
  • Doubly linked list keeps recency order and unlinks in O(1)
  • Move to front on every get and put
  • Evict the node before the tail sentinel
  • Store the key in the node to delete it from the map

Common mistakes

  • Using a singly linked list and scanning for the previous node
  • Forgetting to remove the evicted key from the map
  • Not refreshing recency on update
  • Evicting on update of an existing key

Follow-ups

  • How would you implement an LFU cache?
  • How do you add time-to-live expiry?
  • How would you make this safe for concurrent use?

Tips

  • Explain why each structure alone is not enough
  • Use sentinels to avoid special cases
  • Trace the eviction example

Evaluation rubric

  • Correct O(1) design
  • Correct recency updates
  • Correct eviction and map cleanup
  • Handles capacity edge cases