Versioned Key-Field Store with Expiry and Time Travel
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a timestamped two-level store with expiring values, conditional updates, sorted prefix scans and historical lookups, driven by a batch of operations.
Versioned Key-Field Store
You are simulating a small in-memory store. Each record is addressed by a key (string) and a field (string) and holds an integer value. Every operation carries a timestamp, and timestamps are strictly increasing across the whole sequence of operations.
You are given two parallel lists. operations[i] is the name of the i-th operation and arguments[i] is its argument list, whose first element is always the timestamp. Process the operations in order and return a list with exactly one result per operation.
Operations
| Operation | Arguments | Behavior | Result |
|---|---|---|---|
set | [t, key, field, value] | Store value at key/field with no expiry, replacing any previous value and clearing any previous expiry. | None |
setWithTtl | [t, key, field, value, ttl] | Same as set, but the value expires at time t + ttl. | None |
get | [t, key, field] | Return the value visible at time t. | the integer, or None if there is none |
compareAndSet | [t, key, field, expected, new_value] | If the value visible at t equals expected, store new_value with no expiry. | True if updated, else False |
compareAndSetWithTtl | [t, key, field, expected, new_value, ttl] | Like compareAndSet, but on success the new value expires at t + ttl. | True if updated, else False |
compareAndDelete | [t, key, field, expected] | If the value visible at t equals expected, delete it. | True if deleted, else False |
scan | [t, key] | List every field under key that has a visible value at t. | list of strings |
scanByPrefix | [t, key, prefix] | Same as scan, restricted to fields whose name starts with prefix. | list of strings |
getWhen | [t, key, field, at] | Return the value that was visible for key/field at the earlier moment at, based on the writes performed so far. | the integer, or None |
Visibility rules
- A value written at time
wwith a TTL is visible at timexonly whenx < w + ttl. It is visible atw + ttl - 1and not visible atw + ttl. - A value written without a TTL never expires.
- A deleted value is not visible. A deleted field can be set again later, and the deletion still counts as a write when answering
getWhen. - A missing key or field has no visible value.
- A comparison against
expectedonly succeeds when a value is visible and equalsexpected. An expired, deleted or missing value never matches. - A failed
compareAndSet,compareAndSetWithTtlorcompareAndDeletechanges nothing.
Scan output
- Each entry has the form
"field(value)", for example"age(21)". - Entries are sorted in ascending alphabetical (string) order of the field name.
- Return an empty list if the key does not exist or no field qualifies.
- With
prefix = "",scanByPrefixbehaves likescan.
getWhen
Look at the most recent write to this key/field whose write time is at most at. Return its value if it is visible at time at under the rules above. Return None if there is no such write, if that write was a deletion, or if it had already expired by at.
For example, if 10 is set at time 10 with a TTL of 2 and 18 is set at time 18, then asking about time 5 gives None, time 11 gives 10, time 15 gives None, and time 20 gives 18.
Constraints
len(operations) == len(arguments), and every operation name is one of the nine listed above.- Timestamps in the first position of each argument list are strictly increasing across the sequence.
- Keys, fields and prefixes are strings. Values,
expected,new_valueandttlare integers. - For
getWhen, theatargument is an integer timestamp. - Aim for roughly logarithmic time per
getWhenand at most a sort of one key's fields per scan.
Examples
Example 1
Input: run_versioned_store(['set', 'get', 'setWithTtl', 'get', 'get', 'set', 'getWhen', 'getWhen', 'getWhen', 'getWhen'], [[1, 'a', 'x', 10], [2, 'a', 'x'], [10, 'a', 'x', 10, 2], [11, 'a', 'x'], [12, 'a', 'x'], [18, 'a', 'x', 18], [19, 'a', 'x', 5], [19, 'a', 'x', 11], [19, 'a', 'x', 15], [20, 'a', 'x', 20]])
Output: [None, 10, None, 10, None, None, 10, 10, None, 18]
Example 2
Input: run_versioned_store(['set', 'compareAndSet', 'get', 'compareAndDelete', 'get'], [[1, 'user', 'age', 20], [2, 'user', 'age', 20, 21], [3, 'user', 'age'], [4, 'user', 'age', 21], [5, 'user', 'age']])
Output: [None, True, 21, True, None]
Hints
Hint 1
Keep two structures: one holding the latest record for each key/field, and one append-only list of every write per key/field. Because timestamps only increase, each list is already sorted by time.
Hint 2
Treat deletion as a special write (a tombstone with no value) rather than removing data, and write one visibility check, 'not a tombstone and (no expiry or t < expiry)', that every operation reuses. Do not evict anything eagerly; just test expiry at read time.
Hint 3
For getWhen, binary-search the per-field list of write times for the last write at or before `at`, then apply the same visibility check at time `at`. Keep a separate list of timestamps so the search stays logarithmic.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because timestamps strictly increase, every write to a given key/field arrives in time order. That lets us keep a simple append-only history per key/field and use binary search on it.
We maintain two structures:
- Latest records:
key -> {field -> (written_at, value, expires_at)}. This answersget, the compare operations,scanandscanByPrefix. - History: for each
(key, field), an append-only list of all records, plus a parallel list of just the write times. This answersgetWhen.
All mutations go through one write helper that updates both structures:
- A plain set stores
expires_at = None. - A TTL set stores
expires_at = t + ttl. - A delete stores a tombstone (
value = None). It is kept in the history so that a latergetWhencorrectly sees the field as absent after the deletion, even if an older value exists.
A single visibility predicate is used everywhere:
visible(record, t) = record exists, is not a tombstone,
and (no expiry or t < expires_at)
Expiry is lazy: nothing is removed when time passes, and each read just evaluates the predicate at the time of the call. Since time never goes backward, an expired value can never become visible again, so this is always correct.
Operations
getreads the latest record and returns its value if visible.- The compare operations use the same read. A missing, deleted or expired value reads as
None, so it never equals an integerexpected. On success they callwrite(a value, a value with TTL, or a tombstone). scanisscanByPrefixwith an empty prefix. Sort the field names under the key, keep those that match the prefix and are visible, and format each asfield(value).getWhenfinds the last write with time<= atusingbisect_right(times, at) - 1. If none exists, returnNone. Otherwise return that record's value if it is visible at timeat, which also handles tombstones and values that expired beforeat.
Why it is correct
The value of a field at any instant at is determined entirely by the most recent write at or before at: later writes have not happened, and earlier ones were overwritten. That write is visible exactly when it is not a tombstone and has not expired by at. Binary search over the time-ordered history finds this write. The latest record is just the last history entry, so get and getWhen share identical semantics.
Complexity
Let F be the number of fields under a key and H the number of writes to one field.
set,setWithTtl,get, and the compare operations: O(1) average.scan,scanByPrefix: O(F log F) for sorting, plus the prefix checks.getWhen: O(log H).- Space: O(total number of writes), since history is never pruned.
Reference solution
from bisect import bisect_right
from typing import List
def run_versioned_store(operations: List[str], arguments: List[List]) -> List:
current = {} # key -> {field: (ts, value, expires_at)}
times = {} # (key, field) -> [ts, ...]
records = {} # (key, field) -> [(ts, value, expires_at), ...]
results = []
def visible(record, t):
return (record is not None and record[1] is not None
and (record[2] is None or t < record[2]))
def read(key, field, t):
record = current.get(key, {}).get(field)
return record[1] if visible(record, t) else None
def write(t, key, field, value, expires_at):
record = (t, value, expires_at)
current.setdefault(key, {})[field] = record
times.setdefault((key, field), []).append(t)
records.setdefault((key, field), []).append(record)
for op, args in zip(operations, arguments):
if op == "set":
t, key, field, value = args
write(t, key, field, value, None)
results.append(None)
elif op == "setWithTtl":
t, key, field, value, ttl = args
write(t, key, field, value, t + ttl)
results.append(None)
elif op == "get":
t, key, field = args
results.append(read(key, field, t))
elif op == "compareAndSet":
t, key, field, expected, new_value = args
if read(key, field, t) == expected:
write(t, key, field, new_value, None)
results.append(True)
else:
results.append(False)
elif op == "compareAndSetWithTtl":
t, key, field, expected, new_value, ttl = args
if read(key, field, t) == expected:
write(t, key, field, new_value, t + ttl)
results.append(True)
else:
results.append(False)
elif op == "compareAndDelete":
t, key, field, expected = args
if read(key, field, t) == expected:
write(t, key, field, None, None)
results.append(True)
else:
results.append(False)
elif op == "scan" or op == "scanByPrefix":
if op == "scan":
t, key = args
prefix = ""
else:
t, key, prefix = args
fields = current.get(key, {})
results.append([
f"{field}({fields[field][1]})"
for field in sorted(fields)
if field.startswith(prefix) and visible(fields[field], t)
])
elif op == "getWhen":
t, key, field, at = args
ts_list = times.get((key, field), [])
recs = records.get((key, field), [])
idx = bisect_right(ts_list, at) - 1
if idx < 0:
results.append(None)
else:
rec = recs[idx]
results.append(rec[1] if visible(rec, at) else None)
else:
raise ValueError(f"Unknown operation: {op}")
return results