Simulate a TTL-Aware LRU Cache with Operation Log
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests ability to simulate a fixed-capacity LRU cache where entries expire after a per-entry TTL, processing a sequence of GET/PUT/DELETE operations.
TTL-Aware LRU Cache Simulation
You are given a cache capacity and a list of operations to replay against a TTL-aware LRU cache. The cache stores string keys mapped to integer values. Each entry has a time-to-live (TTL) measured in abstract time units.
Cache Rules
- Capacity: The cache holds at most
capacitylive entries. An entry that has expired does not count toward capacity. - Time: Each operation carries a non-negative integer timestamp
t. Operations are given in non-decreasing timestamp order. - Expiry: An entry inserted (via
PUT) at timetwith TTLttlis live during the interval[t, t + ttl). At timet + ttland beyond it is considered expired and must not be returned byGET. - LRU eviction: When a
PUTwould exceedcapacity(counting only live entries), evict the least recently used live entry. "Recently used" means the last time that key was the target of a successfulGETor aPUT. Expired entries are removed silently before eviction is considered. GETsemantics: Returns the value for the key if the key exists and is live at timet; otherwise returns-1. A successfulGET(key found and live) updates that key's LRU position.PUTsemantics: Inserts or updates the key with the new value and new TTL starting at timet. This counts as a "use" for LRU purposes. If the key already exists (live or expired), it is replaced in-place (its LRU rank is refreshed).DELETEsemantics: Removes the key immediately if present (live or expired); does nothing otherwise. Returns nothing meaningful.
Input
capacity: int # 1 ≤ capacity ≤ 100
operations: list # each element is one of:
["GET", t, key]
["PUT", t, key, value, ttl]
["DELETE", t, key]
1 ≤ capacity ≤ 1000 ≤ t ≤ 10_000(non-decreasing within the list)- Keys are non-empty strings of lowercase letters, length 1–20
- Values are integers in
[-10_000, 10_000] 1 ≤ ttl ≤ 10_0001 ≤ len(operations) ≤ 2_000
Output
Return a list of integers — one entry per GET operation (in order), each being the value returned by that GET (or -1 if the key is absent or expired).
Constraints
1 ≤ capacity ≤ 1000 ≤ t ≤ 10_000, non-decreasing1 ≤ len(operations) ≤ 2_0001 ≤ ttl ≤ 10_000
Examples
Example 1
Input: simulate_ttl_lru_cache(2, [['PUT', 0, 'a', 10, 5], ['PUT', 0, 'b', 20, 5], ['GET', 1, 'a'], ['GET', 1, 'b'], ['PUT', 1, 'c', 30, 10], ['GET', 2, 'a'], ['GET', 2, 'b'], ['GET', 2, 'c']])
Output: [10, 20, -1, 20, 30]
Example 2
Input: simulate_ttl_lru_cache(2, [['PUT', 0, 'x', 1, 3], ['PUT', 0, 'y', 2, 3], ['GET', 1, 'x'], ['PUT', 2, 'z', 3, 10], ['GET', 2, 'x'], ['GET', 2, 'y'], ['GET', 2, 'z'], ['GET', 4, 'x']])
Output: [1, 1, -1, 3, -1]
Example 3
Input: simulate_ttl_lru_cache(3, [['PUT', 0, 'a', 5, 10], ['PUT', 0, 'b', 6, 10], ['PUT', 0, 'c', 7, 10], ['DELETE', 1, 'b'], ['GET', 1, 'b'], ['GET', 1, 'a'], ['PUT', 2, 'd', 8, 10], ['GET', 2, 'a'], ['GET', 2, 'c'], ['GET', 2, 'd']])
Output: [-1, 5, 5, 7, 8]
Hints
Hint 1
Use an OrderedDict (or equivalent doubly-linked structure) to track LRU order; move a key to the end on every successful GET or PUT.
Hint 2
Before any PUT that would exceed capacity, first sweep out all expired entries (by current time), then evict the front (LRU) of the OrderedDict if still needed.
Hint 3
Store (value, insert_time, ttl) per key so you can check liveness as `insert_time <= t < insert_time + ttl` at any query time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We maintain an OrderedDict where the front is the least-recently-used entry and the back is the most-recently-used. Each value stored in the dict is [value, insert_time, ttl], which lets us check liveness with a simple comparison.
Operation handling
GET(t, key)
- Check if the key exists and
insert_time <= t < insert_time + ttl. - If live: move it to the end (MRU), append its value to results.
- Otherwise: append
-1. (We don't eagerly remove the expired entry here; that happens at the next PUT.)
PUT(t, key, value, ttl)
- If the key already exists (whether live or expired): overwrite its entry and
move_to_endto refresh LRU rank. - If the key is new:
- Purge expired: scan the dict and remove all entries that are not live at time
t. This frees up slots without burning LRU evictions. - Evict LRU: while the number of remaining (live) entries ≥ capacity, pop the front (
popitem(last=False)). - Insert the new key at the end.
- Purge expired: scan the dict and remove all entries that are not live at time
DELETE(t, key)
- Simply
del cache[key]if present; no-op otherwise.
Correctness
- LRU order is maintained exactly: every successful GET and every PUT (new or update) moves the key to the MRU end.
- Expiry is checked against the stored
(insert_time, ttl)at the precise timestamp of each operation, so stale entries are never surfaced through GET. - Capacity counts only live entries because we purge expired entries before checking capacity on a PUT.
- Re-PUT of an existing key (even if expired) is treated as an update and does not trigger eviction of other keys, matching the spec ("replaced in-place, LRU rank refreshed").
Complexity
- Time: O(N · C) in the worst case where N is the number of operations and C is the cache capacity (purge step scans up to C entries). With C ≤ 100 and N ≤ 2,000 this is at most 200,000 steps — well within limits.
- Space: O(C) for the cache itself.
from collections import OrderedDict
def simulate_ttl_lru_cache(capacity: int, operations: list) -> list:
# cache maps key -> [value, insert_time, ttl]
# OrderedDict preserves LRU order: least-recently-used at front (first), MRU at end (last)
cache = OrderedDict()
results = []
def is_live(entry, t):
_, insert_time, ttl = entry
return insert_time <= t < insert_time + ttl
def purge_expired(t):
dead = [k for k, v in cache.items() if not is_live(v, t)]
for k in dead:
del cache[k]
for op in operations:
if op[0] == "GET":
_, t, key = op
if key in cache and is_live(cache[key], t):
cache.move_to_end(key)
results.append(cache[key][0])
else:
results.append(-1)
elif op[0] == "PUT":
_, t, key, value, ttl = op
if key in cache:
cache[key] = [value, t, ttl]
cache.move_to_end(key)
else:
purge_expired(t)
while len(cache) >= capacity:
cache.popitem(last=False) # evict LRU
cache[key] = [value, t, ttl]
cache.move_to_end(key)
elif op[0] == "DELETE":
_, t, key = op
if key in cache:
del cache[key]
return results