sagelearnai

LRU Cache

Difficulty: Medium · Pattern: Linked List · LeetCode #146

Design a Least Recently Used cache with a fixed capacity:

  • get(key): return the value if present (this counts as a use), else −1.
  • put(key, value): insert or update the key (also a use). If this pushes the size above capacity, evict the least recently used key.

Both operations must run in O(1) average time.

Example

text
LRUCache(2); put(1,1); put(2,2); get(1) → 1; put(3,3)  (evicts 2)
get(2) → −1; put(4,4)  (evicts 1); get(1) → −1; get(3) → 3; get(4) → 4

Hints

  1. A hash map gives O(1) lookup, but how do you know which key is least recently used?
  2. Keep keys in a list ordered by recency, and move a key to the front on every use. A doubly linked list makes the moves O(1).
  3. The map stores key → list node, so you can unlink a node directly.

Approach

Combine a hash map (key → node) with a doubly linked list ordered from most to least recently used, using sentinel head/tail nodes to avoid edge cases.

  • get: look up the node, move it to the front, and return its value.
  • put: update and move to the front if present; otherwise insert a new node at the front, and if over capacity, remove the node before the tail sentinel (the LRU) and delete it from the map.

In Python, collections.OrderedDict (with move_to_end and popitem(last=False)) implements exactly this. JavaScript's Map preserves insertion order, so delete-and-reinsert works as a compact alternative. Interviewers often ask for the explicit linked-list version, shown in Python below.

Complexity

Time: O(1) average per operation. Space: O(capacity).

Python solution
class Node:
    __slots__ = ("key", "val", "prev", "next")
    def __init__(self, key=0, val=0):
        self.key, self.val, self.prev, self.next = key, val, None, None

class LRUCache:
    def __init__(self, capacity):
        self.cap, self.map = capacity, {}
        self.head, self.tail = Node(), Node()        # sentinels: head <-> ... <-> tail
        self.head.next, self.tail.prev = self.tail, self.head

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

    def _push_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 not node:
            return -1
        self._unlink(node); self._push_front(node)
        return node.val

    def put(self, key, value):
        if key in self.map:
            node = self.map[key]; node.val = value
            self._unlink(node); self._push_front(node)
            return
        node = Node(key, value); self.map[key] = node; self._push_front(node)
        if len(self.map) > self.cap:
            lru = self.tail.prev
            self._unlink(lru); del self.map[lru.key]
JavaScript solution
class LRUCache {
  constructor(capacity) { this.cap = capacity; this.map = new Map(); }  // Map keeps insertion order
  get(key) {
    if (!this.map.has(key)) return -1;
    const v = this.map.get(key);
    this.map.delete(key); this.map.set(key, v);      // move to most-recent end
    return v;
  }
  put(key, value) {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    if (this.map.size > this.cap) this.map.delete(this.map.keys().next().value);  // oldest
  }
}