LRU Cache
mediumTests passed 2026-11-11v1.0.01. Core Invariant / The Trick
Combine a HashMap (`key -> Node`) for O(1) lookup with an insertion/recency doubly-linked list (with dummy `head`/`tail` sentinels) so promotion to MRU and eviction from LRU both run in O(1).
2. Complexity Bounds & Proof
Hash lookup + pointer splice at head/tail executes fixed instructions per `get`/`put`; memory is bounded by capacity C.
3. Minimal Idiomatic Code
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.cap:
self.cache.popitem(last=False)4. Failure Modes & Interview Follow-ups
Pitfalls:- Updating an existing key in `put` must promote it to MRU and NOT trigger capacity eviction if already present.
- Built-in Map iteration order in JS/Python `OrderedDict` works cleanly too, but interviewers often ask for the manual DLL.
Follow-ups:- LFU Cache uses frequency buckets (Map of frequency -> doubly-linked list) plus `minFreq` tracking.
Personal Notes & Scratchpad (Local-First Yjs CRDT)
Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.
Related Invariants
Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.