1/37
Part 1 of 6 · Two limitsLearn

A TTL cache and an LRU cache

Netflix candidates report a key-value cache with a time to live, and for one of them the whole prompt was a single line (3 sources). Anthropic candidates report an LRU cache that comes in parts (2 reports). They start like this:

A cache with a time to live

Build TTLCache. put(key, value, ttl) stores a value that stays live for ttl seconds. get(key, default=None) returns a live value, or default. Read the time from a clock you're given, so a test can move it by hand.

TimeCallReturns
0put("a", 1, ttl=10)
9.9get("a")1
10get("a")None, because it was written at 0 with a TTL of 10

An LRU cache

Build LRUCache(capacity). get(key) returns the value and makes the key the most recently used. put(key, value) adds or updates a key, and when a new key overflows the cache, the least recently used entry goes.

Call, with capacity 2Returns
put("a", 1), then put("b", 2)
get("a")1, and now b is the least recently used
put("c", 3)evicts b
get("b")None

Each one grows from there. The TTL cache adds cleanup that costs only what it removes, then a size limit. The LRU cache adds a key for a function call's arguments, then a log on disk so the cache survives a crash.

You don't write them yet. Both rest on the two limits every cache has: it runs out of room, and its copies go stale, and the lesson starts there. At the end you solve each problem, level by level, in an interview simulation with a timer: 45 minutes for the TTL cache and 60 for the LRU cache.

This lesson builds on the database lesson's records and time windows, and on two coding patterns: a dict for every lookup, and a heap of deadlines from the heaps lesson for the expiry sweep.