Design an LRU cache
Two structures, because neither alone gives you both operations in O(1). A hash map for lookup by key, and a doubly linked list for recency order — the map stores the node, so touching an entry unlinks and relinks it in constant time, and eviction is whatever sits at the tail.
Overview
Why one structure is not enough
A dictionary gives O(1) lookup and knows nothing about order. A list keeps order and needs O(n) to find and remove an arbitrary element. The requirement is both at once, so you carry both.
The join between them is the important part: the map's value is not the cached value, it is the node in the linked list. That is what lets you go from a key straight to its position and unlink it without walking anything.
Step through it
What to watch
- A
getis not read-only — it changes the order. - Eviction always takes the oldest, which is why order must be maintained.
- The map stores the node, which is what makes unlinking O(1).
Say this out loud
"Hash map plus doubly linked list. The map gives O(1) lookup and holds the node itself, so I can unlink it in O(1) without scanning. Most recent at the head, evict from the tail. In Python I'd reach for OrderedDict and move_to_end."