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

API and data

The contract first, then the data that serves it.

The public surface

CallReturnsChanges the order?Notes
LruCache(capacity)A cacheError below 1
get(key, default)The value, or the defaultYes, on a hitNever loads
put(key, value)The pair that had to go, or nothingYesNever evicts on an update
peek(key)The value, or nothingNoFor layers and tests
remove(key)Was it there?No, the others keep theirsTwice is fine
len(cache)Number of entriesNoO(1)

Why it looks like this

  1. 1

    No nodes outside

    A caller with a node could keep one that is gone.

  2. 2

    No containsKey before get

    Two calls with a gap. One get with a default says the same.

  3. 3

    put tells who went

    Layers can react without a listener inside the core.

  4. 4

    No setCapacity

    If asked: shrink by evicting in a loop, grow by changing one number.

Should put return something?

BreaksThe old value of the key, mixed with the evicted one
How
Whatever left.
Limit
The caller cannot tell an update from an eviction.
Choose when
Never.
WorksNothing
How
As in the puzzle.
Limit
Evicted values that need closing are lost.
Choose when
Plain data.
StrongThe evicted pair, or nothing
How
One optional pair.
Limit
Most callers ignore it.
Choose when
A core that layers build on.