Skip to content

LRU Cache

MediumLeetCode #146Time O(1) per operationSpace O(capacity)

Build a cache with a fixed capacity. get(key) returns the value or -1 if absent. put(key, value) inserts or updates. When a put pushes the size past capacity, evict the least recently used key. Both get and put count as a “use”. Both must run in O(1) average time.

capacity 2: put(1,1) put(2,2) get(1)->1 put(3,3) (evicts 2) get(2)->-1

Two needs pull in opposite directions. You need to find a key in O(1), which is a hash map. You also need to know the usage order and move any entry to “most recent” in O(1), which a map can’t do. A doubly linked list can: if you hold a node, you can unlink it and reinsert it at the front without searching.

So combine them. The list is ordered from most to least recent. The map goes from key to list node. get looks up the node, moves it to the front and returns its value. put puts a new node at the front, and if the size is over capacity, drops the node just before the tail. Two sentinel nodes (fake head and tail) mean you never check for null neighbors. Each node also stores its key, so eviction can delete the map entry.

In an interview, OrderedDict (Python) or LinkedHashMap (Java) does all this in a few lines. Mention it, but expect to be asked to build it by hand.

Show solutionHide solution
class Node:
def __init__(self, key=0, val=0):
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.nodes = {} # key -> node, for O(1) lookup
self.head, self.tail = Node(), Node() # sentinels: head.next is the most recent
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node: Node) -> None:
node.prev.next, node.next.prev = node.next, node.prev
def _push_front(self, node: Node) -> None:
node.prev, node.next = self.head, self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key: int) -> int:
if key not in self.nodes:
return -1
node = self.nodes[key]
self._unlink(node)
self._push_front(node) # now the most recently used
return node.val
def put(self, key: int, value: int) -> None:
if key in self.nodes:
self._unlink(self.nodes[key])
node = self.nodes[key] = Node(key, value)
self._push_front(node)
if len(self.nodes) > self.capacity:
lru = self.tail.prev # least recently used sits before the tail sentinel
self._unlink(lru)
del self.nodes[lru.key]
  • Time: O(1) per operation — a hash lookup plus a constant number of pointer changes.
  • Space: O(capacity) — at most capacity nodes and map entries exist at once.
  • Updating an existing key must also refresh its recency. Here it unlinks the old node first, so the size doesn’t grow and nothing is wrongly evicted.
  • Storing the key in each node. Without it you can’t remove the evicted node’s entry from the map.
  • Pointer order when relinking. Set the new node’s prev and next before changing its neighbors’ pointers. Draw it out once.
  • A failed get changes nothing. Return -1 without touching the list.

Evict the least frequently used key, breaking ties by least recent. The trick: keep a map from key to node and a map from frequency to a doubly linked list of keys with that frequency, plus the current minimum frequency. Each use moves a key up one list.

Implement get, addAtHead, addAtTail, addAtIndex and deleteAtIndex. The trick: the same sentinel nodes used here make every insert and delete branch-free.

Insert Delete GetRandom O(1) (LeetCode 380)

Section titled “Insert Delete GetRandom O(1) (LeetCode 380)”

Support insert, remove and random pick in O(1). The trick: another map-plus-structure pairing: an array for random access and a map from value to array index. To remove, swap the element with the last one and pop.