Reconstruct Versioned Key-Value Store from Operation Log
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests the ability to replay a sequential log of set/delete operations on a key-value store and answer point-in-time value queries efficiently.
Versioned Key-Value Store
You are given a log of operations applied, in order, to an initially empty key-value store. Each operation is one of:
| Operation | Format | Effect |
|---|---|---|
SET | ["SET", key, value] | Sets key to value at this version |
DEL | ["DEL", key] | Deletes key at this version |
Operations are numbered 1-indexed (the first operation is version 1, the second is version 2, etc.).
After replaying the full log you receive a list of queries. Each query is [key, version] and asks:
What was the value of
keyimmediately after operation numberversionwas applied?
Rules:
- If
keyexisted (wasSETand not yetDEL-ed) at that version, return its value (always a non-empty string). - If
keydid not exist at that version (never set, or most recently deleted), returnNone. - A
DELon a key that does not exist is a no-op (it still consumes a version number). - Version numbers in queries are guaranteed to be between 1 and
len(ops)inclusive.
Implement query_versioned_store(ops, queries) which returns a list of answers (strings or None) in the same order as the queries.
Constraints
1 ≤ len(ops) ≤ 20001 ≤ len(queries) ≤ 2000- Each operation is either
["SET", key, value]or["DEL", key] - All keys and values are non-empty strings consisting of lowercase letters and digits
keylength ≤ 20,valuelength ≤ 50- Query versions are integers in
[1, len(ops)]
Examples
Example 1
Input: query_versioned_store([['SET', 'name', 'alice'], ['SET', 'age', '30'], ['DEL', 'name'], ['SET', 'name', 'bob']], [['name', 1], ['name', 3], ['name', 4], ['age', 2], ['age', 5]])
Output: ['alice', None, 'bob', '30', '30']
Example 2
Input: query_versioned_store([['SET', 'x', '10'], ['DEL', 'x'], ['DEL', 'x'], ['SET', 'x', '20']], [['x', 1], ['x', 2], ['x', 3], ['x', 4]])
Output: ['10', None, None, '20']
Example 3
Input: query_versioned_store([['SET', 'a', '1'], ['SET', 'b', '2'], ['SET', 'a', '3']], [['a', 1], ['a', 2], ['a', 3], ['b', 1], ['b', 3], ['c', 2]])
Output: ['1', '1', '3', None, '2', None]
Hints
Hint 1
For each key, keep a sorted list of (version, value_or_sentinel) events so you can binary-search to the right version later.
Hint 2
Use a special sentinel (e.g., None) to record DEL events in the history, so a binary search returns None for deleted keys.
Hint 3
Build the per-key history during a single pass over ops, then answer every query in O(log n) with bisect_right.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
For each key, maintain a chronological list of change events — each event records the version at which the change occurred and the resulting value (or None for a deletion). Because we process operations in order, this list is naturally sorted by version.
To answer a query (key, ver), we need the most recent event for that key at or before version ver. This is a classic predecessor search on the event list, which binary search handles in O(log n).
Algorithm
-
Build per-key histories (single pass over
ops):- For version
i(1-indexed), inspect the operation. SET key value→ append(i, value)tohistory[key].DEL key→ append(i, None)tohistory[key]. If the key was never set, still record the event (harmless, and maintains the invariant that the list covers all mutations).
- For version
-
Answer each query
(key, ver):- If
keyhas no history, returnNone. - Binary search
history[key]for the rightmost event whose version ≤ver(usebisect_righton the version column, subtract 1). - If no such event exists (index < 0), return
None; otherwise return the stored value (which may itself beNonefor a past deletion).
- If
Correctness
- Events are stored in strictly increasing version order (each operation gets a unique index), so binary search always finds the correct predecessor.
Nonevalues stored for DEL events naturally propagateNoneback to the caller, correctly signalling "key did not exist at this version."- DEL on a nonexistent key still inserts
(ver, None), which is fine — any query at that version will seeNoneeither way.
Complexity
- Time: O(N log N + Q log N) where N = number of ops and Q = number of queries. Building histories is O(N); each query is O(K) to extract versions (can be O(log K) with a more elaborate structure, but K ≤ N so this is fine for the given constraints).
- Space: O(N) for the history maps.
import bisect
def query_versioned_store(ops: list, queries: list) -> list:
history = {}
for i, op in enumerate(ops):
version = i + 1
if op[0] == "SET":
_, key, value = op
if key not in history:
history[key] = []
history[key].append((version, value))
else: # DEL
_, key = op
if key not in history:
history[key] = []
history[key].append((version, None))
results = []
for key, ver in queries:
if key not in history:
results.append(None)
continue
events = history[key]
versions = [e[0] for e in events]
idx = bisect.bisect_right(versions, ver) - 1
if idx < 0:
results.append(None)
else:
results.append(events[idx][1])
return results