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

Entities

Three classes, and five that stay out

The point: three classes earn their place, because each hides something the others need not know.

Three that earn their place

  • LruCache

    Hides that there are two structures. Outside there is only a key and a value.

  • RecencyList

    Hides every pointer. Outside there is only front, back, touch.

  • Node

    A record with neighbours. It stays private: whoever holds a node could break the list.

Five that do not, and what to say

CandidateVerdictSay
CacheManagerOut"The cache manages itself. A manager would only pass calls on."
EvictionStrategyLater"One policy today. I keep touch and last apart, so a policy can be lifted out when there is a second."
CacheEntry next to NodeOut"They would have the same life and the same fields."
Cache interfaceWith the first layer"It pays when something wraps the cache: a lock, a clock, a counter."
BuilderWith the sixth option"One number in the constructor needs no builder."

Who owns a node?

In Java, Python and TypeScript the garbage collector decides. In C++ you must: the map owns each node with a unique_ptr, the list only links them with plain pointers. Two owners would free it twice, none would leak it. Saying this shows that you see the two structures as an owner and a view.

What does get return on a miss?

Breaks-1 for every cache
How
As in the integer version of the puzzle.
Limit
-1 may be a real value, and for text it makes no sense.
Choose when
Only where values are known to be positive.
WorksNone or null
How
The common answer of the language.
Limit
A stored null looks like a miss, so nulls must be forbidden.
Choose when
Most code. Say that nulls are refused.
StrongAn optional, or a default chosen by the caller
How
get(key, default) or Optional<V>.
Limit
A little more to type.
Choose when
A library class. With a private sentinel as default even None can be stored.