Cache Eviction
01 / The shared mechanism
A fixed-capacity store with O(1) get and put. The trick is the data structure: every eviction policy is a different answer to which entry do I drop when the cache is full? Two classic ones share the same O(1) trick — LRU pairs a hash map with a doubly-linked list so the just-touched key can be moved to the front in constant time; LFU tracks per-key frequency in buckets so the lowest-frequency bucket is always reachable in O(1).
02 / The one-sentence essence
The just-touched node moves to the head; the tail is the eviction candidate. Hash map gives O(1) lookup; doubly-linked list gives O(1) splice. Together: O(1) per op.
03 / The pattern signature
04 / When to recognize this pattern
05 / Common pitfalls
del map[evicted.key] — otherwise the map still claims the cache holds that key, and a later get happily returns a stale node that no longer lives in the list. The list and the map have to stay in lock-step.size > capacity, not ≥. Insert first, then evict if overflowed — that way you always have room for the new node. Flip the order or the comparison and you either lose the newly inserted entry or never evict at all.06 / Go practice — on LeetCode
Four problems. LRU Cache is the canonical implementation. LFU Cache keeps the same map + linked-list trick but stacks one more layer to track frequency. All O`one generalizes the move-to-front mechanic to handle both min and max in O(1). First Unique Number applies the same hash + linked structure to a streaming uniqueness problem.