Design an LRU cache
medium 85 minDesign 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
| Choice | Reason | Cost | Change it when |
|---|---|---|---|
| Map and own list | Shows and controls the order | Forty lines | Production: use the library |
| Two sentinels | No special cases | Two nodes | Never |
| Evict before insert | The limit always holds | One comparison | Never |
| One lock | Easy to prove | One call at a time | A profile shows waiting |
| Layers | Features combine | One more call each | Every nanosecond counts |
| LRU | Follows change, simple | Scans flush it | Your 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.