Simulate a Time-Aware Key-Value Store with Transactions
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests implementation of an in-memory store combining TTL expiration, a logical clock, and atomic single-transaction semantics with rollback.
Problem
Build a function that simulates an in-memory key-value store driven by a sequence of commands. The store tracks a logical clock and supports expiring keys, plus a single-level transaction that can be committed or discarded.
Commands
| Command | Arguments | Returns | Description |
|---|---|---|---|
SET | key, value, ttl | nothing | Stores value under key. The entry expires at current_time + ttl (exclusive). |
GET | key | value or None | Returns the stored value if the key exists and has not expired; otherwise None. |
DELETE | key | nothing | Removes the key. No-op if the key is absent. |
BEGIN | — | nothing | Opens a transaction. All subsequent writes are staged and not yet visible outside the transaction. |
COMMIT | — | nothing | Flushes all staged writes into the committed store and closes the transaction. |
ROLLBACK | — | nothing | Discards all staged writes and closes the transaction, leaving the committed store unchanged. |
TICK | — | nothing | Advances the logical clock by 1. |
Expiration rule
A key set at time t with a TTL of d expires at t + d. It is visible only while current_time < t + d. At the moment current_time == t + d the key is already gone.
Transaction semantics
- At most one transaction is active at any moment.
- While a transaction is open,
GETreads staged writes first; if the key is not staged it falls back to the committed store. - A
DELETEissued inside a transaction hides the key from subsequentGETcalls within that same transaction, even if the key exists in the committed store. COMMITmakes all staged changes permanent.ROLLBACKabandons them.TICKalways advances the clock, even inside a transaction. Time is never rolled back.
Your task
Implement the function below. It receives two parallel lists:
commands— a list of command strings, each one of the seven names above.args— a list of argument lists. Commands that take no arguments have an empty list[].SEThas three elements;GETandDELETEhave one; the rest have none.
Return a list of results, one per command. Commands that produce no output contribute None to the result list. GET contributes either the value string or None.
Constraints
1 ≤ len(commands) ≤ 1000- All keys and values are non-empty strings.
ttlis a positive integer.- The logical clock starts at
0before any command runs. BEGINis never called while a transaction is already open.COMMITandROLLBACKare always called with an active transaction.
Examples
Example 1
Input: run_expiring_store(['SET', 'TICK', 'GET', 'BEGIN', 'SET', 'GET', 'ROLLBACK', 'GET'], [['a', '1', 10], [], ['a'], [], ['a', '2', 5], ['a'], [], ['a']])
Output: [None, None, '1', None, None, '2', None, '1']
Hints
Hint 1
Track absolute expiry times (time_of_set + ttl) rather than counting down a remaining TTL — then an expiry check is a single comparison at read time regardless of how many ticks have passed.
Hint 2
A DELETE inside a transaction cannot simply remove the key from the staging area, because the key may still exist in the committed store and would reappear on the next GET. Use a sentinel value (e.g. None) in the staging dict to mean 'deleted in this transaction'.
Hint 3
On COMMIT, iterate the staging dict and apply each entry to the committed store: a sentinel becomes a deletion, anything else becomes an upsert. On ROLLBACK, just throw the staging dict away — the committed store was never touched.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core data structures
Two dictionaries do all the work:
store— the committed state, mapping each key to a(value, expires_at)pair.staging— the uncommitted writes of the active transaction, orNonewhen no transaction is open.
Expiry is stored as an absolute clock value (time_of_write + ttl). A key is alive when current_time < expires_at. This means an expiry check is always a single integer comparison, no matter how many ticks have passed since the key was written.
The tombstone pattern
The trickiest part is DELETE inside a transaction. Simply removing the key from staging would not work: the key might still exist in store, and a subsequent GET would fall through and return the committed value — which should be hidden. Instead, a sentinel object (_DELETED) is stored in staging for that key. Any GET that finds the sentinel returns None immediately, without consulting store.
How each command works
- SET / DELETE — if a transaction is open, write to
staging; otherwise write directly tostore. - GET — if a transaction is open, check
stagingfirst. A sentinel or an expired staged entry returnsNone. A live staged entry returns its value. If the key is not instaging, fall back tostoreand apply the same expiry check. - BEGIN — set
stagingto an empty dict. - COMMIT — iterate
staging: sentinels become deletions instore; real entries become upserts. Then setstaging = None. - ROLLBACK — set
staging = None.storewas never touched, so the committed state is intact with zero extra work. - TICK — increment the clock. This happens unconditionally, even mid-transaction, and is never undone by a rollback.
Why this is correct
Isolation. store is never modified while staging is open. Rollback is therefore O(1): discarding staging restores the exact committed state.
Read-your-writes. Inside a transaction, staging is checked before store, so every write made in the transaction is immediately visible to subsequent reads within the same transaction.
Commit equivalence. staging keeps only the last write per key. Applying that final write produces the same result as replaying every intermediate write in order, because each later write on the same key fully supersedes the earlier one.
Expiry consistency. Expiry times are set at write time and are absolute, so a key that expires between SET and COMMIT will simply be invisible after commit — the same behavior as if it had been written directly to store.
Complexity
| Operation | Time |
|---|---|
TICK, BEGIN, ROLLBACK | O(1) |
SET, GET, DELETE | O(1) average (hash map) |
COMMIT | O(k), where k is the number of distinct keys staged in the transaction |
Space: O(n + k) — n live (or not-yet-purged) entries in store plus k staged entries. Expired keys that are never read again linger in store until a GET touches them (lazy expiration). A heap keyed by expires_at could proactively evict them if memory is a concern.
Worked trace of the sample
time=0 SET("a","1",10) → store: {"a": ("1", 10)}
time=0 TICK → time=1
time=1 GET("a") → 1 < 10, returns "1"
time=1 BEGIN → staging={}
time=1 SET("a","2",5) → staging: {"a": ("2", 6)}
time=1 GET("a") → found in staging, 1 < 6, returns "2"
time=1 ROLLBACK → staging=None; store unchanged
time=1 GET("a") → no staging; store has ("1",10); 1 < 10, returns "1"
Full solution
from typing import List, Optional
def run_expiring_store(commands: List[str], args: List[List[object]]) -> List[Optional[str]]:
_DELETED = object() # sentinel: key was deleted inside the active transaction
time = 0
store = {} # key -> (value, expires_at)
staging = None # None when no transaction is open; dict otherwise
results = []
for command, arg in zip(commands, args):
if command == "TICK":
time += 1
results.append(None)
elif command == "SET":
key, value, ttl = arg
entry = (value, time + ttl)
if staging is None:
store[key] = entry
else:
staging[key] = entry
results.append(None)
elif command == "GET":
key = arg[0]
# Check staging layer first when a transaction is open
if staging is not None and key in staging:
entry = staging[key]
if entry is _DELETED or entry[1] <= time:
results.append(None)
else:
results.append(entry[0])
else:
entry = store.get(key)
if entry is None or entry[1] <= time:
results.append(None)
else:
results.append(entry[0])
elif command == "DELETE":
key = arg[0]
if staging is None:
store.pop(key, None)
else:
staging[key] = _DELETED
results.append(None)
elif command == "BEGIN":
staging = {}
results.append(None)
elif command == "COMMIT":
for key, entry in staging.items():
if entry is _DELETED:
store.pop(key, None)
else:
store[key] = entry
staging = None
results.append(None)
elif command == "ROLLBACK":
staging = None
results.append(None)
return results