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

Requirements

Sentences that become methods

The point: each requirement should be visible in one place of the code. If you cannot point at it, it is not met.

What it must do

RequirementDetailWhere
CreateFixed capacity, at least 1. Anything else is an error at once__init__
GetThe value, or nothing. A hit makes the key the most recentget
Put, new keyStores the pair at the front. If full, the least recent goes firstput, _evict
Put, known keyNew value, most recent, nobody is evictedput, first branch
EvictFrom both structures, and tell the caller who went_evict
RemoveOptional: forget one key. Needed for expiry and invalidationremove
PeekOptional: look without changing the orderpeek

How well it must do it

QualityTargetHow you would show it
TimeO(1) on average for get and putNo loop in either of them
MemoryO(capacity), never above, not even for a momentEvict before insert
No leaksA removed node is reachable from nowhereMap entry gone, pointers cleared
ThreadsOptional. If asked, each method is one stepOne lock, then measure
ClarityPointers in one classRecencyList can be tested alone

Eight questions, and a default if nobody answers

QuestionDefaultWhat another answer changes
What does a miss return?Nothing, or a default the caller passes-1 is fine if values are never negative
Which types?Any key that can be hashedIntegers only: an array could replace the map
Can a value be None?Not distinguished from a missReturn an optional, or a private sentinel object
Does writing count as using?YesNo: a put on a known key would not touch
Does reading count as using?Yes, that is LRUNo: it becomes FIFO
Threads?OneA lock, see the FAANG pages
Do entries get old?NoA deadline for each entry
Are entries of similar size?Yes, so we count entriesWeights, and an eviction that may take several

From C.I.M.P.L. to requirements

  • Container

    O(1) lookup, O(1) reordering, a size that is always known.

  • Item

    Key, value, both neighbours. The key is there for the eviction.

  • Manager

    get and put in O(1), and three small helpers: push, unlink, touch.

  • Policy

    Remove the last one. Must be replaceable, need not be pluggable.

  • Lifecycle

    Entry: created, used, evicted. Cache: empty, warm, full. After full it stays full until something is removed.