Expiring Key-Value Store Driven by a Virtual Clock
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate a key-value store with per-key expiry on a manual clock, handling overwrites, deletes and cleanup of expired entries via a command list.
You are building a small in-memory cache where every entry carries its own lifetime. Instead of reading a real clock, the cache runs on a virtual clock that you move forward yourself, so behavior is fully deterministic.
Write a function that takes a list of commands and their arguments, replays them in order against an initially empty store, and returns the result of each command.
Virtual clock
- The clock starts at
0.0. - It changes only through the
advancecommand, which adds the given amount to the current time (use floating-point addition).
Entry lifetime
- A
putat timetwith lifetimettlgives the entry an expiry time oft + ttl. - An entry is live only while
now < expiry. Whennow >= expiry, the entry is expired and must behave as if it does not exist. - Writing a key that already holds a live entry replaces both its value and its expiry. The old lifetime is discarded completely.
- Writing a key whose previous entry has already expired simply creates a fresh entry.
- A stored value may be
None. A lookup of such a key and a lookup of a missing key both returnNone, and that is acceptable here.
Commands
Each command is a string, and the matching element of params is its argument list.
| Command | Arguments | Effect | Result recorded |
|---|---|---|---|
"put" | [key, value, ttl] | Store the value with the given lifetime. | None |
"get" | [key] | Look up the key. | The value if the key has a live entry, otherwise None |
"delete" | [key] | Remove the key. | True if a live entry was removed, otherwise False |
"advance" | [amount] | Move the clock forward by amount. | None |
"cleanup" | [] | Physically discard every expired entry. | None |
"size" | [] | Count the entries that are currently live. | The count (an integer) |
Expired entries must never be observable. Before processing any command, entries whose expiry time is at or before the current time must already be treated as gone. Deleting a key whose entry has already expired returns False.
Task
Implement the function so it returns a list with one result per command, in order. Beyond correctness, a good solution should not rescan the whole store to find expired entries, and should not let stale bookkeeping grow without bound when keys are overwritten or deleted repeatedly.
Constraints
len(commands) == len(params).- Every command is one of the six listed above, with the argument shape shown.
- Keys are strings. Values are arbitrary (including
None). ttlis a positive number.advanceamounts are non-negative numbers.- The number of commands can be large, so aim for roughly
O(log n)amortized work per command.
Examples
Example 1
Input: process_ttl_commands(['put', 'get', 'advance', 'get', 'delete', 'size'], [['a', 10, 5], ['a'], [5], ['a'], ['a'], []])
Output: [None, 10, None, None, False, 0]
Example 2
Input: process_ttl_commands(['put', 'put', 'get', 'advance', 'get', 'size'], [['x', 'old', 10], ['x', 'new', 3], ['x'], [2], ['x'], []])
Output: [None, None, 'new', None, 'new', 1]
Example 3
Input: process_ttl_commands(['put', 'get', 'advance', 'cleanup', 'size'], [['nullable', None, 4], ['nullable'], [4], [], []])
Output: [None, None, None, None, 0]
Example 4
Input: process_ttl_commands(['get', 'delete', 'put', 'advance', 'put', 'get'], [['missing'], ['missing'], ['k', 1, 2], [2], ['k', 2, 5], ['k']])
Output: [None, False, None, None, None, 2]
Hints
Hint 1
Keep a dictionary from key to its current entry (expiry, value). Because an expired entry must act as absent, run an expiry sweep before handling every command.
Hint 2
Use a min-heap ordered by expiry time so the sweep only touches entries that are actually due. Overwrites and deletes cannot cheaply remove items from the heap, so leave the old records there.
Hint 3
Give each put a unique version number and store it in both the dictionary entry and the heap record. When a heap record is popped, delete the key only if the dictionary still holds that same expiry and version; otherwise the record is stale and is ignored.
Hint 4
Stale heap records can pile up under many overwrites or deletes. When the heap grows well beyond the number of stored keys, rebuild it from the dictionary and heapify.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two structures:
- A dictionary
storemapping each key to(expiry, version, value). This answersget,deleteandsizedirectly. - A min-heap of
(expiry, version, key)records ordered by expiry time. This lets us find entries that are due without scanning everything.
Every put gets a fresh, increasing version number. It writes the entry into the dictionary and pushes a matching record onto the heap.
Before every command, and again after advance, we run a sweep: while the earliest heap record has expiry <= now, pop it. If the dictionary still holds an entry for that key with the same expiry and version, delete it. Otherwise the record is stale (the key was overwritten or deleted since) and is simply discarded.
Because the sweep runs before each command, every command sees a store where expired entries are already gone. That gives the exact boundary rule: an entry with now == expiry is removed, so it is not live.
Why it is correct
- Overwrite: the new entry has a new version and expiry. The old heap record no longer matches the dictionary entry, so when it comes due it is ignored and the new entry survives.
- Delete: the key leaves the dictionary at once, and its heap record becomes stale and is ignored later.
deletereturnsTrueonly if the key was present, and since expired entries were swept first, a present key is always live. - Stored
Nonevalues: entries are tuples, so presence is tested on the tuple, not on the value. Deleting a live key holdingNonecorrectly returnsTrue. - Never-read keys: the heap lets the sweep reclaim them with no
getrequired.
Bounding stale records
Overwrites and deletes leave stale records in the heap. When the heap exceeds 2 * len(store) + 64 records, it is rebuilt from the dictionary and re-heapified. That costs O(m) for m live keys but happens only after Omega(m) stale records have accumulated, so it is amortized O(1) per operation, and heap memory stays proportional to the live data.
Complexity
- Each record is pushed once and popped at most once, so sweeping is
O(log n)amortized per command. putisO(log n);get,deleteandsizeareO(1)plus the sweep.- Space is
O(n)fornlive entries, thanks to the rebuild rule. - A burst of keys expiring together can cause a long pause in one command, though the amortized cost stays the same.
Reference solution
import heapq
from typing import List
def process_ttl_commands(commands: List[str], params: List[List[object]]) -> List[object]:
now = 0.0
version_counter = 0
store = {} # key -> (expiry, version, value)
heap = [] # (expiry, version, key), may contain stale records
results = []
def rebuild_if_bloated():
if len(heap) > 2 * len(store) + 64:
heap[:] = [(e[0], e[1], k) for k, e in store.items()]
heapq.heapify(heap)
def sweep():
while heap and heap[0][0] <= now:
expiry, version, key = heapq.heappop(heap)
current = store.get(key)
if current is not None and current[0] == expiry and current[1] == version:
del store[key]
rebuild_if_bloated()
for command, args in zip(commands, params):
sweep()
if command == "put":
key, value, ttl = args
version_counter += 1
expiry = now + float(ttl)
store[key] = (expiry, version_counter, value)
heapq.heappush(heap, (expiry, version_counter, key))
rebuild_if_bloated()
results.append(None)
elif command == "get":
entry = store.get(args[0])
results.append(None if entry is None else entry[2])
elif command == "delete":
removed = store.pop(args[0], None) is not None
results.append(removed)
rebuild_if_bloated()
elif command == "advance":
now += float(args[0])
sweep()
results.append(None)
elif command == "cleanup":
sweep()
results.append(None)
elif command == "size":
sweep()
results.append(len(store))
else:
raise ValueError("unknown command")
return results