Versioned Key-Value Store with Global Version Tracking
Data Structure DesignAuto-graded · 19 test casesLast updated
Implement a key-value store where each write increments a global version counter and reads retrieve values by version using binary search.
Build a key-value store that maintains a global version number incremented with every write operation. The store supports two operations:
Set Operation: set(key, value) writes a value to a key, assigns it the next available global version number (starting from 1), and returns that version number.
Get Operation: get(key, version) retrieves the value that was most recently written to the key at or before the specified version. If no value has been written to the key at or before that version, return None.
You are given a sequence of operations to process. Each operation is either a set or get, with corresponding arguments. Return a list containing the result of each operation: for set operations, return the assigned version number; for get operations, return the retrieved value or None.
Important details:
- The global version counter starts at 1 and increments by 1 with each
setoperation - Each key maintains its own sparse history of (version, value) pairs
- A
get(key, version)finds the write with the largest version number ≤ the requested version - If a key has never been written, or if all writes to that key occurred after the requested version, return
None
Constraints
- 1 ≤ number of operations ≤ 10^5
- Keys are non-empty strings
- Values are integers
- Version numbers in
getoperations are positive integers - All operations must be processed in order
Examples
Example 1
Input: versioned_kv_store(['set', 'set', 'get', 'get', 'get'], [['a', 10], ['b', 20], ['a', 1], ['a', 2], ['b', 1]])
Output: [1, 2, 10, 10, None]
Example 2
Input: versioned_kv_store(['get', 'set', 'get', 'set', 'get', 'get'], [['missing', 1], ['x', 7], ['x', 1], ['x', 9], ['x', 2], ['x', 99]])
Output: [None, 1, 7, 2, 9, 9]
Example 3
Input: versioned_kv_store(['set', 'set', 'set', 'get', 'get', 'get'], [['k', 1], ['k', 2], ['k', 3], ['k', 2], ['k', 3], ['k', 100]])
Output: [1, 2, 3, 2, 3, 3]
Hints
Hint 1
Each key needs to store a chronological list of (version, value) pairs as writes occur.
Hint 2
For a get operation, you need to find the rightmost version in the key's history that doesn't exceed the requested version.
Hint 3
Binary search can efficiently locate the correct historical entry if you search on the version numbers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to maintain a single global version counter that increments with each write, while each key independently tracks its own sparse history of writes.
Data Structure:
- Use a dictionary mapping each key to a list of (version, value) tuples
- Maintain a global counter that starts at 1 and increments after each
set - Each key's history is automatically sorted by version since writes are processed sequentially
Set Operation: Append the current global version and the provided value to the key's history list, return the version number, then increment the counter.
Get Operation:
To find the value at a requested version, use binary search on the key's version history. Specifically, use bisect_right to find the insertion point for the requested version, then look at the entry immediately to the left (index - 1). This gives us the largest version that doesn't exceed the requested version. If no such entry exists (index would be 0 or negative, or the key has no history), return None.
Why Binary Search Works: Since versions are assigned sequentially and each key's history is append-only, the version numbers in each key's history form a sorted list. Binary search efficiently locates the predecessor version in O(log n) time where n is the number of writes to that specific key.
Complexity:
- Time: O(1) for each
set, O(log w) for eachgetwhere w is the number of writes to that key - Space: O(total writes) to store all historical values
Solution
from bisect import bisect_right
from typing import List, Optional
def versioned_kv_store(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
key_histories = {}
current_version = 1
results = []
for op, args in zip(operations, arguments):
if op == "set":
key, value = args
if key not in key_histories:
key_histories[key] = []
key_histories[key].append((current_version, value))
results.append(current_version)
current_version += 1
elif op == "get":
key, version = args
if key not in key_histories:
results.append(None)
continue
history = key_histories[key]
version_list = [v for v, _ in history]
pos = bisect_right(version_list, version) - 1
if pos < 0:
results.append(None)
else:
results.append(history[pos][1])
return results