LRU Cache With Expiry
Extend an LRU cache so that every entry expires. The clock is passed in: each call carries the current time now, and now never decreases from one call to the next.
new ExpiringCache(capacity)creates a cache that holds at mostcapacitylive entries (capacity >= 1).put(key, value, ttl, now)inserts or updateskey. The entry expires atnow + ttl; from that moment on it behaves as if it were not there.get(key, now)returns the value when the key is present and has not expired, and-1otherwise.
Rules
- A successful
get, and anyput, makes that key the most recently used. - A
puton a live key updates its value, its expiry and its recency. Aputon a missing or expired key is a fresh insert. - Expired entries do not occupy capacity. When a fresh insert finds
capacitylive entries, evict the least recently used live entry; an expired entry is never the reason a live one is evicted.
cache = new ExpiringCache(2)
put("a", 1, 100, 0) put("b", 2, 5, 0)
put("c", 3, 100, 10) // b expired at 5, so nothing live is evicted
get("a", 10) -> 1 get("b", 10) -> -1 get("c", 10) -> 3Be ready to explain what you would do when the cache's miss rate is high.
Hints
Hint 1
Start from the plain LRU: a hash map plus recency order (a doubly linked list, or a Map whose insertion order you maintain by deleting and re-inserting).
Hint 2
Lazy expiry handles get: check the entry's expiry when it is read, and delete it if it is past.
Hint 3
Lazy expiry alone gets eviction wrong. In the example, the least recently used entry is a, but the entry that should make room is the expired b. Something has to find expired entries without scanning: a min-heap ordered by expiry time.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.