DEV Community

Anurag Goel
Anurag Goel

Posted on Originally published at algosimplified.dev

LRU Cache (LeetCode 146) Design in Python and Java

This article first appeared on AlgoSimplified. That URL is canonical. The full lesson has the complete Java class, follow-up sketches, exercises and a short quiz. This is a shorter cut of the same design.

The problem

A cache with fixed capacity. get(key) returns the value (or a miss) and marks the key as recently used. put(key, value) inserts or updates; if the cache is full, it evicts the least recently used key. Both operations must be O(1).

A hash map gives O(1) lookup but no order. A list gives order, but moving an item to the front is O(n) unless you can reach its neighbours directly.

The combination that works is a hash map from key to node, plus a doubly linked list ordered from most to least recently used. The map finds the node; the links let you unlink it and move it in O(1).

head <-> [4] <-> [3] <-> tail
          MRU           LRU
map = {4: node4, 3: node3}
Enter fullscreen mode Exit fullscreen mode

Sentinel head and tail nodes remove the empty-list special cases. Every real node always has non-null neighbours.

Python

"""LRU cache with O(1) get and put: hash map + doubly linked list."""


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:
    def __init__(self, capacity: int):
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.map: dict = {}  # key -> Node
        self.head, self.tail = Node(), Node()  # sentinels: head.next is most recent
        self.head.next, self.tail.prev = self.tail, self.head

    def _unlink(self, node: Node):
        node.prev.next, node.next.prev = node.next, node.prev

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

    def get(self, key, default=-1):
        node = self.map.get(key)
        if node is None:
            return default
        self._unlink(node)  # mark as most recently used
        self._push_front(node)
        return node.value

    def put(self, key, value):
        node = self.map.get(key)
        if node is not None:
            node.value = value
            self._unlink(node)
            self._push_front(node)
            return
        if len(self.map) == self.capacity:
            lru = self.tail.prev  # least recently used sits just before the tail
            self._unlink(lru)
            del self.map[lru.key]
        node = Node(key, value)
        self.map[key] = node
        self._push_front(node)

    def keys_mru_to_lru(self):
        out, n = [], self.head.next
        while n is not self.tail:
            out.append(n.key)
            n = n.next
        return out


if __name__ == "__main__":
    c = LRUCache(2)
    c.put(1, "one")
    c.put(2, "two")
    print(c.get(1))           # one  (1 becomes most recent)
    c.put(3, "three")         # evicts 2
    print(c.get(2))           # -1
    c.put(4, "four")          # evicts 1
    print(c.get(1), c.get(3), c.get(4))  # -1 three four
    print("order:", c.keys_mru_to_lru())
Enter fullscreen mode Exit fullscreen mode

Output:

one
-1
-1 three four
order: [4, 3]
Enter fullscreen mode Exit fullscreen mode

After get(1), key 1 is most recent, so put(3) evicts 2, not 1. After put(4), 1 is gone and the list is 4 then 3.

Java

The Java in the full lesson is the same structure, generic over key and value: sentinel head and tail, HashMap<K, Node<K, V>>, unlink and pushFront, with get and put marked synchronized.

Two differences are worth noting:

  • A miss returns null, not -1. The run prints one, then null, then null three four.
  • synchronized makes each method atomic. A read/write lock would not help: get also rewrites the list, so every operation is a write to the ordering.

The lesson records that same output from javac / java LRUCache.

Library shortcuts and common follow-ups

  • Python: collections.OrderedDict with move_to_end(key) and popitem(last=False); functools.lru_cache for memoising functions.
  • Java: LinkedHashMap with accessOrder=true and an overridden removeEldestEntry.

In interviews, it is usually enough to mention the shortcut, then implement the linked list unless you are told otherwise.

Common follow-ups:

  • Throughput: one lock serialises everything. Shard by key hash into N segments, each with its own lock and capacity (approximate LRU, much higher throughput).
  • TTL: store an expiry on the node; treat expired entries as misses, and optionally sweep in the background.
  • LFU: evict the least frequently used key. An O(1) design keeps a map of frequency to a doubly linked list, plus a min_freq pointer.
  • Distributed cache: that becomes an HLD question. The caching lesson in the System Design course covers that side. Redis itself offers approximate LRU eviction.

This is also LeetCode 146, and it appears on the LeetCode 150 sheet.

The list has to be doubly linked, because unlinking in O(1) needs a pointer to the previous node. The full LRU lesson has the complete Java, exercises (TTL, a sharded cache, LFU) and a short quiz, as part of the free Low-Level Design course.

Top comments (0)