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

How to approach it

What this question tests, where it gets hard, and how to spend the time.

What this problem tests

  • Choosing structures

    From the operations to the structures, aloud, and not from memory.

  • Pointer care

    Four writes in the right order. Draw them.

  • An invariant

    Two structures, one truth.

  • Concurrency sense

    Seeing that a read writes.

  • Change

    Time, weight and policy as layers.

Spend the 45 minutes

MinutesDoHave at the end
0 to 4Contract and questionsget, put, a miss, capacity
4 to 9Reject slow ideas, choose two structuresA drawing of head, nodes, tail and the map
9 to 24Code: node, list, get, putSomething that runs
24 to 29Trace: hit, update when full, eviction, capacity 1A bug found by yourself, or none
29 to 41Threads, then one extensionOne lock, its price, one layer
41 to 45Tests and what you would do nextThe invariant as a test

If you are stuck

H, D, L

Hash map to find. Doubly linked so that a node can leave from the middle. List with the most recent at the head and the least recent at the tail. Three letters, and each has a reason you can give.

Sounds like this

  • "Two questions, two structures."
  • "I write unlink and push once."
  • "Known before full."

Not like this

  • "I remember this one."
  • Five null checks in unlink
  • A lock before the code works