Time-Versioned Key-Value Storage
Data Structure DesignAuto-graded · 14 test casesLast updated
Implement a data structure that stores versioned values by timestamp and retrieves the most recent version at or before a query time.
Build a time-versioned storage system that records string values for string keys at integer timestamps. The system must handle updates arriving in any order and efficiently answer queries for the current or historical state.
Implement a function time_versioned_store(operations, arguments) that processes a sequence of operations on a versioned store:
"LatestValueStore"with[]: Initialize or reset the store. OutputNone."set"with[key, value, timestamp]: Record thatkeyhadvalueattimestamp. Updates may arrive out of chronological order. If the same(key, timestamp)pair is stored multiple times, the most recent call's value takes precedence. OutputNone."get"with[key]or[key, timestamp]: Return the value forkeywith the largest timestamp that does not exceedtimestamp. IftimestampisNoneor omitted, return the value with the largest timestamp overall. If no qualifying entry exists, return"".
The function receives two parallel lists: operations contains operation names, and arguments contains the corresponding argument lists. Return a list of outputs, one per operation.
Performance matters: with up to 200,000 operations, scanning all history per query will exceed time limits.
Constraints
1 <= len(key), len(value) <= 50keyandvaluecontain only lowercase letters, digits, and underscores1 <= timestamp <= 10^9- At most
2 * 10^5total operations - Updates can arrive in arbitrary timestamp order
Examples
Example 1
Input: time_versioned_store(['LatestValueStore', 'set', 'set', 'set', 'get', 'get', 'get', 'get'], [[], ['device_1', 'standby', 10], ['device_1', 'active', 20], ['device_1', 'idle', 5], ['device_1'], ['device_1', 15], ['device_1', 4], ['device_2']])
Output: [None, None, None, None, 'active', 'standby', '', '']
Example 2
Input: time_versioned_store(['LatestValueStore', 'set', 'set', 'set', 'get', 'get', 'get'], [[], ['status', 'yellow', 100], ['status', 'red', 100], ['status', 'green', 50], ['status', 100], ['status'], ['status', 75]])
Output: [None, None, None, None, 'red', 'red', 'green']
Hints
Hint 1
For each key, maintain its timeline in a structure that supports efficient predecessor queries—finding the largest timestamp not exceeding a target value.
Hint 2
Binary search can locate the correct version in logarithmic time if timestamps are kept sorted. Consider how to maintain sorted order as new timestamps arrive.
Hint 3
When the same (key, timestamp) pair is updated twice, only the storage value needs updating—avoid duplicating the timestamp in your sorted structure.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each key maintains its own version history. A query asking for the state at time t needs to find the most recent update at or before t—this is a predecessor search problem on the timeline.
We maintain two structures per key:
- Sorted timestamp list: holds all distinct timestamps where this key was updated, kept in ascending order
- Timestamp-to-value map: provides O(1) lookup and update for any specific timestamp
When storing a value:
- If this is a new timestamp for the key, insert it at the correct sorted position using binary search (
bisect_right) - If the timestamp already exists, simply update the value in the map (the sorted list already contains it, avoiding duplicates)
When retrieving:
- For queries without a timestamp (or
None), the maximum timestamp is simply the last element of the sorted list—O(1) access - For queries with a specific timestamp
t, usebisect_right(times, t) - 1to find the index of the largest timestamp ≤t. If this index is negative, all recorded timestamps exceedt, so return""
This design handles out-of-order updates naturally because insertion maintains the sorted invariant immediately. Overwrites at the same timestamp only touch the value map, not the sorted list.
Correctness
The sorted list always contains exactly the keys present in the value map, with no duplicates. bisect_right finds the insertion point for a value or counts how many elements are ≤ t. Subtracting one gives the index of the largest element ≤ t, which is precisely the predecessor we need. When multiple updates occur at the same timestamp, the last one wins because we overwrite the map entry.
Complexity
Let n be the number of distinct timestamps for a given key.
- set (new timestamp): O(log n) binary search + O(n) list insertion in worst case
- set (overwrite): O(1)
- get (with timestamp): O(log n) binary search
- get (latest): O(1) list tail access
Space: O(total distinct (key, timestamp) pairs)
In practice, list insertion via insert() is a single memory move operation and performs well within the 200,000 operation limit. For guaranteed O(log n) insertions, a balanced tree structure like SortedList from sortedcontainers could replace the list.
from bisect import bisect_right
from typing import List, Optional
def time_versioned_store(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
time_index = {}
store = {}
output = []
for op, args in zip(operations, arguments):
if op == "LatestValueStore":
time_index.clear()
store.clear()
output.append(None)
elif op == "set":
key, value, ts = args
if key not in time_index:
time_index[key] = []
store[key] = {}
times = time_index[key]
if ts not in store[key]:
pos = bisect_right(times, ts)
times.insert(pos, ts)
store[key][ts] = value
output.append(None)
else: # "get"
key = args[0]
if key not in time_index or not time_index[key]:
output.append("")
continue
times = time_index[key]
if len(args) == 1 or args[1] is None:
ts = times[-1]
else:
pos = bisect_right(times, args[1]) - 1
if pos < 0:
output.append("")
continue
ts = times[pos]
output.append(store[key][ts])
return output