Skip to content
BytePatterns

LRU Cache With Expiry

MediumLow-Level Design#ordered-dict#lazy-expiry#min-heap~30m

Problem

Design a cache class that holds at most capacity entries, where every entry also has a time to live. put(key, value, ttl, now) stores a value that expires at now + ttl, replacing any older value for the key. get(key, now) returns the value, or None once now has reached the expiry time, and a successful get makes the entry the most recently used. When a put finds the cache full, it must first throw away entries that have already expired, and only if that frees nothing may it evict the least recently used live entry. Time is passed in as a number so the behaviour is deterministic and testable.

Examples

Input:  capacity 2; put("a", 1, ttl=10, now=0), put("b", 2, ttl=100, now=0)
        get("a", now=5), put("c", 3, ttl=100, now=6), get("b", now=7), get("a", now=7)
Output: [1, None, 1]
Why:    the get at 5 made "a" recent, so "b" was the one evicted for "c"
Input:  then get("a", now=10)
Output: None
Why:    "a" expired at exactly 10
Input:  then put("d", 4, ttl=5, now=20), put("e", 5, ttl=5, now=26), get("c", now=27), get("d", now=27)
Output: [3, None]
Why:    edge case, "d" had already expired, so it was dropped and "c" survived even though it was older

Hints

0 / 3

Stuck on the idea rather than the code? LRU Cache covers it.