TRACK B · ALGORITHMmedium•NOVEMBER 2026•7 MIN
LRU Cache: O(1) Lookup, Promotion & Eviction
Combine a Hash Map and Doubly Linked List to get O(1) get, O(1) put, and O(1) eviction—a bridge between coding and system design.
lru cachehash maplinked listcachingdesigndata-structures
The core idea
A hash map gives O(1) lookup by key; a doubly linked list gives O(1) unlink-from-middle and insert-at-head. Pairing them builds the core eviction engine inside real caches.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING LRU CACHE SIM...
What to say out loud
Canonical Python template
from collections import OrderedDict
class LRUCache:
def __init__(self, cap: int):
self.cap = cap
self.od: OrderedDict[str, int] = OrderedDict()
def get(self, key: str) -> int:
if key not in self.od:
return -1
self.od.move_to_end(key)
return self.od[key]
def put(self, key: str, val: int) -> None:
self.od[key] = val
self.od.move_to_end(key)
if len(self.od) > self.cap:
self.od.popitem(last=False)