KatInterview

Simulate a TTL-Aware LFU Cache with Frequency Snapshots

Data Structure DesignAuto-graded · 15 test cases
HardAuto-gradedData Structure Designdata structurescachesimulation

Last updated

Tests ability to simulate a multi-operation Least-Frequently-Used cache that evicts expired entries by TTL and breaks ties by recency, while supporting frequency-snapshot queries.

TTL-Aware LFU Cache with Frequency Snapshots

You are given a series of operations to simulate on a Least-Frequently-Used (LFU) cache that also enforces time-to-live (TTL) expiry on every entry.

Cache Rules

  1. Capacity – The cache holds at most capacity keys at any time.
  2. TTL – Every PUT associates a TTL (in time units). An entry expires at the moment current_time >= insert_time + ttl. Expired entries are invisible: GET misses on them and they are removed lazily (or eagerly — your choice) before any eviction decision.
  3. LFU eviction – When a PUT would exceed capacity (after removing any expired keys), evict the key with the lowest use-count. Use-count is the total number of PUT + GET operations that hit that key (the initial PUT counts as 1). Ties in use-count are broken by least-recently-used (smallest timestamp of last access).
  4. Re-PUT – Putting a key that already exists (and has not expired) updates its value, resets its TTL (from the current timestamp), and increments its use-count by 1. If the key has already expired, treat it as a brand-new insert.
  5. GET – Returns the value for a live key and increments its use-count by 1. Returns None if the key is absent or expired.

Operations

Each operation is a dict with a "type" field:

typeextra fieldsdescription
"PUT""key" (str), "value" (int), "ttl" (int ≥ 1), "time" (int)Insert/update entry
"GET""key" (str), "time" (int)Retrieve entry
"SNAPSHOT""time" (int)See below

SNAPSHOT Operation

A SNAPSHOT returns a list of [key, value, use_count] triples for all currently live (non-expired) keys at the given time, sorted by:

  1. use_count descending
  2. key lexicographically ascending (tie-break)

Input / Output

def lfu_cache_sim(capacity: int, operations: list[dict]) -> list
  • operations is a list of operation dicts as described above.
  • Return a flat list of all results in order:
    • PUT → append None
    • GET → append the retrieved value or None
    • SNAPSHOT → append one sublist [[key, value, use_count], ...] (may be empty)

Constraints

  • 1 ≤ capacity ≤ 200
  • 1 ≤ len(operations) ≤ 2 000
  • All "time" values are non-negative integers; operations are given in non-decreasing time order.
  • "key" strings are non-empty and contain only lowercase letters and digits.
  • "value" is any integer; "ttl" ≥ 1.
  • TTL expiry: entry expires when current_time >= insert_time + ttl.
  • If all live entries tie on use-count during eviction, the one with the smallest last-access timestamp is evicted.
  • A SNAPSHOT at time T does not count as an access; it does not affect use-counts or last-access timestamps.
  • Times within operations are non-decreasing but multiple operations may share the same timestamp.

Examples

Example 1

Input: lfu_cache_sim(2, [{'type': 'PUT', 'key': 'a', 'value': 1, 'ttl': 10, 'time': 0}, {'type': 'PUT', 'key': 'b', 'value': 2, 'ttl': 10, 'time': 1}, {'type': 'GET', 'key': 'a', 'time': 2}, {'type': 'PUT', 'key': 'c', 'value': 3, 'ttl': 10, 'time': 3}, {'type': 'GET', 'key': 'b', 'time': 4}, {'type': 'GET', 'key': 'c', 'time': 5}, {'type': 'SNAPSHOT', 'time': 6}])

Output: [None, None, 1, None, None, 3, [['a', 1, 2], ['c', 3, 2]]]

Example 2

Input: lfu_cache_sim(2, [{'type': 'PUT', 'key': 'x', 'value': 10, 'ttl': 3, 'time': 0}, {'type': 'PUT', 'key': 'y', 'value': 20, 'ttl': 10, 'time': 1}, {'type': 'GET', 'key': 'x', 'time': 3}, {'type': 'GET', 'key': 'x', 'time': 4}, {'type': 'SNAPSHOT', 'time': 5}])

Output: [None, None, None, None, [['y', 20, 1]]]

Example 3

Input: lfu_cache_sim(3, [{'type': 'PUT', 'key': 'p', 'value': 5, 'ttl': 5, 'time': 0}, {'type': 'PUT', 'key': 'q', 'value': 6, 'ttl': 5, 'time': 0}, {'type': 'PUT', 'key': 'r', 'value': 7, 'ttl': 5, 'time': 0}, {'type': 'GET', 'key': 'p', 'time': 1}, {'type': 'GET', 'key': 'p', 'time': 2}, {'type': 'GET', 'key': 'q', 'time': 3}, {'type': 'PUT', 'key': 's', 'value': 8, 'ttl': 5, 'time': 4}, {'type': 'SNAPSHOT', 'time': 4}, {'type': 'GET', 'key': 'r', 'time': 10}, {'type': 'SNAPSHOT', 'time': 10}])

Output: [None, None, None, 5, 5, 6, None, [['p', 5, 3], ['q', 6, 2], ['s', 8, 1]], None, []]

Hints

Hint 1

Track per-key: value, use_count, last_access_time, insert_time, and ttl. Before every mutation or eviction, filter out all keys where current_time >= insert_time + ttl.

Hint 2

For eviction, iterate over live keys and pick the one minimizing (use_count, last_access_time) — a min-heap or a simple linear scan over at most `capacity` items both work within the constraints.

Hint 3

Re-PUT on an existing live key must reset insert_time to the current time (for the new TTL window) and increment use_count, not reset it to 1.