Replay an Operation Log to Answer Versioned Key Lookups
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests the ability to simulate a versioned key-value store by replaying a sequence of set/delete operations and answering point-in-time key lookups.
Versioned Key-Value Store
You are given a log of operations applied to a key-value store, along with a list of queries. Each query asks: "What was the value associated with a given key immediately after a specific operation was applied?"
Operations
The operation log is a list of entries. Each entry is a dict with one of two shapes:
| Shape | Meaning |
|---|---|
{"op": "set", "key": <str>, "value": <str>} | Store value under key, overwriting any previous value. |
{"op": "delete", "key": <str>} | Remove key from the store. If the key does not exist, this is a no-op. |
Operations are applied in order, indexed from 1 (the first operation has version 1, the second has version 2, and so on).
Queries
Each query is a dict:
{"key": <str>, "version": <int>}
It asks: after replaying operations 1 through version (inclusive), what is the value of key?
- If
keyexists in the store at that version, return its string value. - If
keydoes not exist (was never set, or was deleted and not re-set), returnNone.
Your Task
Implement a function that accepts the operation log and the list of queries, and returns a list of answers (strings or None) in the same order as the queries.
Queries are independent — each one is answered against the store state at the specified version, not a running state.
Constraints
0 ≤ len(ops) ≤ 20001 ≤ len(queries) ≤ 2000- Each query's
versionsatisfies1 ≤ version ≤ len(ops)(guaranteed;opswill be non-empty when queries exist). - Keys and values are non-empty strings consisting of lowercase letters, digits, and underscores.
- Values in
"set"operations are non-empty strings. - Duplicate keys across operations are allowed; the latest
"set"before or at the queried version wins.
Examples
Example 1
Input: query_versioned_store([{'op': 'set', 'key': 'x', 'value': '10'}, {'op': 'set', 'key': 'y', 'value': '20'}, {'op': 'set', 'key': 'x', 'value': '99'}, {'op': 'delete', 'key': 'y'}], [{'key': 'x', 'version': 1}, {'key': 'x', 'version': 3}, {'key': 'y', 'version': 4}])
Output: ['10', '99', None]
Example 2
Input: query_versioned_store([{'op': 'set', 'key': 'a', 'value': 'hello'}, {'op': 'delete', 'key': 'a'}, {'op': 'set', 'key': 'a', 'value': 'world'}], [{'key': 'a', 'version': 1}, {'key': 'a', 'version': 2}, {'key': 'a', 'version': 3}])
Output: ['hello', None, 'world']
Example 3
Input: query_versioned_store([{'op': 'set', 'key': 'color', 'value': 'red'}, {'op': 'set', 'key': 'size', 'value': 'large'}, {'op': 'delete', 'key': 'color'}, {'op': 'set', 'key': 'color', 'value': 'blue'}], [{'key': 'color', 'version': 2}, {'key': 'color', 'version': 3}, {'key': 'size', 'version': 2}, {'key': 'color', 'version': 4}])
Output: ['red', None, 'large', 'blue']
Hints
Hint 1
For each query, you only need to consider operations up to and including the given version — replaying the prefix of the log up to that version is the simplest correct approach.
Hint 2
A dictionary keyed by operation key tracking the most recent set/delete up to each version is sufficient; you do not need a persistent data structure.
Hint 3
If you sort or group queries by version, you can answer all queries in a single forward pass through the operation log in O(len(ops) + len(queries)) time.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Intuition
Each query is independent and asks for the store state at a specific version (operation prefix). The naive approach — for every query, replay all operations up to its version — is O(V × Q) where V = number of ops and Q = number of queries. For the given constraints (both up to 2 000) that's at most 4 million steps, which is fine, but we can do better with one linear sweep.
Efficient Single-Pass Solution
-
Group queries by version. Build a dictionary mapping each unique version number to the list of
(original_index, key)pairs that need to be answered at that version. -
Sweep through the operation log once (version 1 to len(ops)). Maintain a live
storedictionary:"set"→store[key] = value"delete"→store.pop(key, None)(no-op if absent)
-
After applying operation at version
v, check if any queries are pinned to that version. For each such query, readstore.get(key, None)and record it at the correct output index. -
Return the answers list.
Correctness
Because we process operations strictly in order and snapshot the store at every version boundary where a query exists, each query sees exactly the store state after operations 1…version, which is precisely what is asked.
Complexity
- Time: O(V + Q) — one pass through V operations, one pass through Q queries during grouping, and one answer lookup per query.
- Space: O(K + Q) — K unique keys in the store at peak, plus the grouped-query map and answer array.
from typing import List
def query_versioned_store(ops: list, queries: list) -> list:
if not queries:
return []
# Group query indices by the version they need.
version_to_queries: dict = {}
for i, q in enumerate(queries):
v = q["version"]
if v not in version_to_queries:
version_to_queries[v] = []
version_to_queries[v].append((i, q["key"]))
answers = [None] * len(queries)
store: dict = {} # live key-value store state
for version in range(1, len(ops) + 1):
op = ops[version - 1]
if op["op"] == "set":
store[op["key"]] = op["value"]
elif op["op"] == "delete":
store.pop(op["key"], None)
# Answer any queries pinned to this version
if version in version_to_queries:
for idx, key in version_to_queries[version]:
answers[idx] = store.get(key, None)
return answers