← chapter

LRU cache

Evict the least-recently-used item when full. Hash map + doubly-linked list = O(1) everything.

Two O(1) needs, no single structure

Watch the recency list

put E (full) → evict B (back, least recent). get A → move A to front. The front fills with what you use; the back is what you evict.

Why LRU: hit rate

Skewed (Zipf) workload, cap 50: LRU 71% vs FIFO/random 65%. Recency predicts reuse.

Doubly-linked is load-bearing

Takeaway

Two structures sharing nodes meet a two-part requirement — the composition pattern. OrderedDict / functools.lru_cache ARE this under the hood. Next: k-d trees — nearest-neighbour search by partitioning space.