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

Problem

What is asked, and how to take it apart

The point: the problem is two verbs and one budget. get and put, both O(1), with room for a fixed number of entries.

What they say, and what they mean

The first minute

  1. Interviewer

    Design a cache with a fixed capacity that throws out the least recently used entry.

  2. You

    Two methods, then: get(key) and put(key, value). Does reading count as using?

  3. Interviewer

    Yes. Both reading and writing make a key the most recent.

  4. You

    What should a miss return, and is a put on a known key an update?

  5. Interviewer

    Choose something sensible for a miss. A put on a known key updates it.

  6. You

    Then a miss returns nothing, which is None in Python and an empty optional elsewhere. For a version with positive integers only, minus one is the usual sign. I assume one thread at first and come back to it. Is O(1) expected for both?

  7. Interviewer

    On average, yes.

From a vague sentence to code in five steps

  1. 1

    The contract

    Two methods, a capacity of at least one, what a miss looks like.

  2. 2

    The forbidden loop

    Say it: no walk over the entries in get or put. That excludes most first ideas.

  3. 3

    Two questions, two structures

    Where is it? A map. Who is last? A list.

  4. 4

    Two small operations

    Unlink and push to the front. Write them first and trust them afterwards.

  5. 5

    One invariant

    Map and list hold the same nodes. Check it aloud after each method.

C.I.M.P.L.: five places to look

Container, Item, Manager, Policy, Lifecycle. For a data structure problem, start at the container and the policy: they decide everything else.

LetterQuestionHereIn code
ContainerWhat holds the data?A hash map and a doubly linked list over the same nodes_nodes, _order
ItemWhat is stored?A node: key, value, two neighboursNode
ManagerWho runs it?The cache. It is the only one that changes both structuresLruCache
PolicyWhat could vary?Who goes first: LRU, LFU, FIFO. A method today, an interface when a second one is neededlast(), touch()
LifecycleWhich states?An entry: created, used, evicted. The cache: cold, warm, fullThe place in the list

Good first sentences

  • "I need to find by key and to know who is last, both in O(1)."
  • "One structure cannot do both, so one node lives in two."
  • "I start with one thread and say where threads would hurt."

Sentences that cost you

  • "I will use an ordered dictionary." And then?
  • "A Singleton cache with a strategy factory."
  • "I sort by time stamp when it is full."