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

Explain your choices

Answer first. Then compare your reasoning.

16 questions 0 got it 0 to review16 not marked

Choice, reason, cost, trigger

ChoiceReasonCostChange it when
Map and own listShows and controls the orderForty linesProduction: use the library
Two sentinelsNo special casesTwo nodesNever
Evict before insertThe limit always holdsOne comparisonNever
One lockEasy to proveOne call at a timeA profile shows waiting
LayersFeatures combineOne more call eachEvery nanosecond counts
LRUFollows change, simpleScans flush itYour own trace says so

Own list, OrderedDict, or a library?

BreaksA list of keys beside a dictionary
How
keys.remove(key); keys.append(key).
Limit
remove walks: O(n) for each hit.
Choose when
Never.
WorksOrderedDict, LinkedHashMap
How
Ten lines.
Limit
Does not show that you know why.
Choose when
Real code, small tools.
StrongOwn list in the round, a library in the product
How
Say both sentences.
Limit
None.
Choose when
Always.

One sentinel or two?

BreaksNone
How
first and last may be null.
Limit
Branches in each method.
Choose when
Never under pressure.
WorksTwo
How
head and tail.
Limit
One node more.
Choose when
The drawing is clearer.
StrongOne, as a ring
How
root.next is first, root.prev is last.
Limit
A little harder to explain.
Choose when
You have explained two before.