call(back)
Algorithms & Data StructuresmediumSign in to star problems

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 most capacity live entries (capacity >= 1).
  • put(key, value, ttl, now) inserts or updates key. The entry expires at now + 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 -1 otherwise.

Rules

  • A successful get, and any put, makes that key the most recently used.
  • A put on a live key updates its value, its expiry and its recency. A put on a missing or expired key is a fresh insert.
  • Expired entries do not occupy capacity. When a fresh insert finds capacity live 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) -> 3

Be 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

Similar Problems6