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

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

A map to find, a list to order, one node in both.

A rail for three coats with a board of buttons. The worn coat goes to the front. When a new one comes, the last one goes, and its button with it.

Design an LRU cache in one picture

Cheat sheet

H D L
Hash map, Doubly linked, List: head newest, tail oldest
Node
key, value, prev, next
push
node.prev, node.next, first.prev, head.next
unlink
Neighbours shake hands
put
Known, full, new
Evict
tail.prev, from list and map
Cost
O(1) average, O(capacity) space
Threads
One lock: a read is a write
Redis
Sample 5, evict the idlest

Spot it when you see

  • A fixed number of entries and 'throw out the oldest used'.
  • O(1) lookup and O(1) order at the same time.
  • Move any element to the front.
  • Recently opened files, open connections, loaded pages.

Tricks that stick

  • Say KFN for put: Known, Full, New.
  • Write unlink and push once, then only compose.
  • Check capacity 1 first: it finds most bugs.
  • Expiry looks first (peek), then touches.

Do not forget

  • No touch in get.
  • Map entry left behind after eviction.
  • Full asked before known.
  • A read lock around get.
  • `>` in place of `>=`.
  • Loading or calling listeners under the lock.