This article first appeared on AlgoSimplified . That URL is canonical. The full lesson has the complete Java class, follow-up sketches, exercises and a short quiz. This is a shorter cut of the same design.
The problem
A cache with fixed capacity. get(key) returns the value (or a miss) and marks the key as recently used. put(key, value) inserts or updates; if the cache is full, it evicts the least recently used key. Both operations must be O(1).
A hash map gives O(1) lookup but no order. A list gives order, but moving an item to the front is O(n) unless you can reach its neighbours directly.
The combination that works is a hash map from key to node, plus a doubly linked list ordered from most to least recently used. The map finds the node; the links let you unlink it and move it in O(1).
head <-> [4] <-> [3] <-> tail MRU LRU map = {4: node4, 3: node3}
Enter fullscreen mode
Exit fullscreen mode
Sentinel head and tail nodes remove the empty-list special cases.…