KatInterview

TTL-Aware LRU Cache with Lazy Expiration

Data Structure DesignAuto-graded · 14 test cases
HardAuto-gradedData Structure Designlinked-listshash-mapcache

Last updated

Tests ability to design an O(1) key-value store combining LRU eviction with per-entry time-to-live expiration using a hash map and doubly linked list.

TTL-Aware LRU Cache with Lazy Expiration

Build a fixed-capacity in-memory store where every entry carries its own expiration deadline. The store evicts the least recently used entry when it runs out of room, and treats any entry whose deadline has passed as if it never existed.


Interface

Your implementation must support the following sequence of operations, dispatched by a driver function described below:

put(key, value, ttl, now)  →  None
get(key, now)              →  int

put(key, value, ttl, now)

Stores key with the given value. The entry becomes expired at time now + ttl (i.e., it is valid while the current time is strictly less than now + ttl, and expired once the current time reaches or exceeds now + ttl).

  • If key already exists and has not yet expired: overwrite its value, reset its deadline to now + ttl, and mark it as the most recently used entry. The total number of stored entries does not change, so no eviction occurs.
  • If key already exists but has expired: discard the stale entry completely and treat this as a brand-new insertion.
  • After inserting a fresh entry, if the number of stored entries now exceeds capacity, remove the least recently used entry.

get(key, now)

Returns the stored value for key if it exists and has not yet expired; otherwise returns -1.

  • A successful lookup (non-expired key) promotes that entry to the most recently used position.
  • If the key is found but has expired, remove it and return -1.

Expiration boundary: an entry with deadline d is considered expired whenever now >= d. A ttl of 0 means the entry is expired immediately on any future access.

Eviction semantics: eviction is triggered only by a fresh insertion that pushes the count past capacity. At most one entry is evicted per put. The entry removed is whichever one currently occupies the least recently used position in the store — this may be an entry that has already expired but was never accessed.


Driver function

The judge calls a single function:

def ttl_lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
  • capacity — the maximum number of entries the cache may hold at one time.
  • operations — a list of strings, each either "get" or "put".
  • arguments — a list of argument lists, one per operation:
    • For "get": [key, now]
    • For "put": [key, value, ttl, now]
  • Returns a list of results, one per operation: the integer value (or -1) for "get", and None for "put".

Constraints

  • 1 <= capacity <= 1000
  • 1 <= len(operations) == len(arguments) <= 10 000
  • Each operation is either "get" or "put"
  • All keys, values, ttl, and now values are non-negative integers
  • key, value fit in a 32-bit signed integer
  • ttl >= 0; a ttl of 0 means the entry expires at time now, so any get at or after that time returns -1
  • now >= 0; time values within a single sequence of operations are not guaranteed to be monotonically increasing
  • get arguments: [key, now] — exactly 2 integers
  • put arguments: [key, value, ttl, now] — exactly 4 integers
  • Both get and put must run in O(1) average time

Examples

Example 1

Input: ttl_lru_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 10, 5, 0], [2, 20, 10, 0], [1, 1], [3, 30, 5, 1], [2, 1], [3, 1], [1, 5]])

Output: [None, None, 10, None, -1, 30, -1]

Example 2

Input: ttl_lru_cache(1, ['put', 'get', 'put', 'get', 'get'], [[7, 70, 2, 3], [7, 4], [7, 71, 5, 5], [7, 5], [7, 10]])

Output: [None, 70, None, 71, -1]

Hints

Hint 1

The two data structures you need are a hash map for O(1) key lookup and a doubly linked list to track recency order. Sentinel head and tail nodes eliminate all the edge cases around empty lists and boundary insertions.

Hint 2

You don't need a background thread or a timer to handle expiration. Check whether an entry is stale at the moment you touch it, remove it right then, and treat it as absent — this 'lazy deletion' keeps every operation O(1).

Hint 3

Eviction only needs to happen when a brand-new entry is inserted and the count exceeds capacity. Updating a live key never changes the count. The least recently used entry is always sitting just before the tail sentinel, so removing it is a constant-time pointer swap.