Bits & Caches Hard
LRU Cache (Hash Map + Doubly Linked List)
An LRU cache combines a HashMap with a circular doubly linked list: successful gets and all puts move a node to the front, while overflow removes the least-recent node at the tail.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(1) expected per get/put
AverageO(1) expected per get/put
WorstO(1) list work; HashMap operations can degrade with collisions
SpaceO(capacity)
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Execute get and put operations in order. Trace the map-to-node bindings, sentinel links, recency promotions, value updates, misses, and capacity evictions. The final list is shown from most recently used to least recently used.
- A successful get changes recency; a missed get returns null and leaves the list unchanged.
- Putting an existing key updates its value and promotes the same node without eviction.
- A newly inserted node is linked and mapped before the capacity check; overflow removes the sentinel's previous node.
- The circular sentinel is not a cache entry. The first real node is most recently used and the last real node is least recently used.
- Reinserting a key after it was evicted creates a new node identity.
Algorithm code
JavaLRUCache.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1