Simulate a TTL-Aware LFU Cache with Frequency Snapshots
Data Structure DesignAuto-graded · 15 test casesLast 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
- Capacity – The cache holds at most
capacitykeys at any time. - TTL – Every
PUTassociates a TTL (in time units). An entry expires at the momentcurrent_time >= insert_time + ttl. Expired entries are invisible:GETmisses on them and they are removed lazily (or eagerly — your choice) before any eviction decision. - LFU eviction – When a
PUTwould exceed capacity (after removing any expired keys), evict the key with the lowest use-count. Use-count is the total number ofPUT+GEToperations that hit that key (the initialPUTcounts as 1). Ties in use-count are broken by least-recently-used (smallest timestamp of last access). - 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.
- GET – Returns the value for a live key and increments its use-count by 1. Returns
Noneif the key is absent or expired.
Operations
Each operation is a dict with a "type" field:
| type | extra fields | description |
|---|---|---|
"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:
use_countdescendingkeylexicographically ascending (tie-break)
Input / Output
def lfu_cache_sim(capacity: int, operations: list[dict]) -> list
operationsis a list of operation dicts as described above.- Return a flat list of all results in order:
PUT→ appendNoneGET→ append the retrieved value orNoneSNAPSHOT→ append one sublist[[key, value, use_count], ...](may be empty)
Constraints
1 ≤ capacity ≤ 2001 ≤ 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
SNAPSHOTat timeTdoes not count as an access; it does not affect use-counts or last-access timestamps. - Times within
operationsare 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to faithfully simulate a cache with three interacting mechanisms: capacity enforcement, LFU eviction with LRU tie-breaking, and TTL-based expiry. Because capacity is at most 200 and operations at most 2,000, an O(capacity) linear scan for eviction is perfectly acceptable (O(n · capacity) total = 400,000 operations at worst).
Data Structure
A plain dictionary store maps each key to a record:
{
"value": int,
"use_count": int, # incremented by PUT (initial or re-PUT) and GET hits
"last_access": int, # timestamp of most recent PUT/GET that hit this key
"insert_time": int, # timestamp of the most recent PUT for this key
"ttl": int # set on most recent PUT
}
An entry is live at time t iff t < insert_time + ttl.
Algorithm
Before every operation, call purge_expired(t) which removes all keys where t >= insert_time + ttl. This keeps the store consistent and makes the capacity check accurate.
PUT(key, value, ttl, t)
- Purge expired entries.
- If
keyis already live: update itsvalue, resetinsert_timeandttl(extending the window), and incrementuse_countandlast_access. - Otherwise: if
len(store) == capacity, callevict_one(t)which picksargmin_{k in store} (use_count[k], last_access[k]). Then insert a fresh record withuse_count = 1.
GET(key, t)
- Purge expired entries.
- If
keyin store: incrementuse_count, updatelast_access, return value. - Otherwise: return
None.
SNAPSHOT(t)
- Purge expired entries.
- Collect all
[key, value, use_count]triples, sort by(-use_count, key).
Why It Is Correct
- Expiry is checked lazily but consistently: every operation purges before acting, so no stale entry is ever visible.
- Re-PUT correctly increments (not resets) use_count and resets the TTL clock from the current time.
- The eviction key
(use_count, last_access)minimized lexicographically implements LFU with LRU tie-breaking exactly. - SNAPSHOT is read-only: it does not modify any counts or timestamps.
Complexity
- Time: O(n · capacity) where n = number of operations. Each operation purges at most
capacityentries and evicts at most one. - Space: O(capacity) for the store, O(n) for the result list.
def lfu_cache_sim(capacity: int, operations: list) -> list:
store = {}
results = []
def is_alive(entry, current_time):
return current_time < entry["insert_time"] + entry["ttl"]
def purge_expired(current_time):
dead = [k for k, v in store.items() if not is_alive(v, current_time)]
for k in dead:
del store[k]
def evict_one(current_time):
victim = min(
store.keys(),
key=lambda k: (store[k]["use_count"], store[k]["last_access"])
)
del store[victim]
for op in operations:
t = op["time"]
op_type = op["type"]
if op_type == "PUT":
key = op["key"]
value = op["value"]
ttl = op["ttl"]
purge_expired(t)
if key in store:
entry = store[key]
entry["value"] = value
entry["use_count"] += 1
entry["last_access"] = t
entry["insert_time"] = t
entry["ttl"] = ttl
else:
if len(store) >= capacity:
evict_one(t)
store[key] = {
"value": value,
"use_count": 1,
"last_access": t,
"insert_time": t,
"ttl": ttl,
}
results.append(None)
elif op_type == "GET":
key = op["key"]
purge_expired(t)
if key in store:
entry = store[key]
entry["use_count"] += 1
entry["last_access"] = t
results.append(entry["value"])
else:
results.append(None)
elif op_type == "SNAPSHOT":
purge_expired(t)
snapshot = sorted(
[[k, v["value"], v["use_count"]] for k, v in store.items()],
key=lambda x: (-x[2], x[0])
)
results.append(snapshot)
return results