AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Watch lesson4:49

Grow the design

Start with the smallest system that works. Change it only when something breaks.

Four steps, each forced by a sentence

SentenceForcesPrice
"get in O(1)"A map from key to nodeMemory for the table
"the least recent goes, O(1)"A list in order of useTwo links for each entry
"a hit moves from the middle"Doubly linked, with sentinelsFour writes to push, two to unlink
"the evicted key leaves the map"The key in the nodeOne reference

What is inside the lock, and what is not

The class diagram is on the UML page of the solution. Draw three boxes: cache, list, node.