Historical Key-Value Store with Time-Based Retrieval
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests your ability to build a versioned data store supporting efficient historical lookups through binary search on sorted timestamps.
Build a versioned key-value store that records entries along with their timestamps and retrieves historical values efficiently.
Your task is to implement a function that processes a sequence of operations on this store:
"TimeMap": Initialize or reset the store to an empty state."set": Record a key-value pair along with a timestamp."get": Retrieve the most recent value for a key that was recorded at or before a given timestamp.
The function receives two parallel lists:
operations: a list of operation namesarguments: a list of argument lists, one per operation
Return a list of outputs, one per operation:
"TimeMap"and"set"operations returnNone"get"operations return a string
For a "get" query with a given key and timestamp t, return the value associated with the largest timestamp that is less than or equal to t. If no such entry exists (either the key was never recorded, or all its timestamps exceed t), return an empty string "".
Important guarantee: For any single key, all "set" operations arrive with strictly increasing timestamps.
Constraints
1 <= key.length, value.length <= 1001 <= timestamp <= 10^7- Timestamps for each individual key are strictly increasing across
"set"operations - At most
2 * 10^5total operations will be processed - Keys and values contain only alphanumeric characters
Examples
Example 1
Input: historical_store(['TimeMap', 'set', 'get', 'get', 'set', 'get', 'get'], [[], ['foo', 'bar', 1], ['foo', 1], ['foo', 3], ['foo', 'bar2', 4], ['foo', 4], ['foo', 5]])
Output: [None, None, 'bar', 'bar', None, 'bar2', 'bar2']
Hints
Hint 1
Since timestamps arrive in increasing order for each key, you can maintain them in a sorted list without explicit sorting
Hint 2
Use binary search to quickly locate the largest timestamp that doesn't exceed your query timestamp
Hint 3
Maintain parallel arrays: one for timestamps and one for values, both indexed identically for each key
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that each key maintains a version history, and we need to efficiently find the most recent version at or before a query time. Since timestamps arrive in strictly increasing order for each key, we can maintain a naturally sorted list per key without any sorting overhead.
For each key, store a list of (timestamp, value) pairs. When a "get" query arrives:
- Extract all timestamps for that key
- Use binary search to find the position where the query timestamp would fit
- The entry immediately before that position is the answer
Binary search with bisect_right returns the insertion point for a value in a sorted list. For a query timestamp t, bisect_right gives us the index of the first timestamp strictly greater than t. Subtracting 1 gives us the index of the largest timestamp less than or equal to t, which is exactly what we need.
Edge cases handled:
- If the index is -1, all recorded timestamps are greater than the query, so return
"" - If the key doesn't exist, treat it as an empty history and return
"" - If the query timestamp exactly matches a recorded timestamp,
bisect_rightcorrectly includes it
Why It Works
The correctness relies on maintaining a sorted invariant: timestamps for each key remain in strictly increasing order. Since the problem guarantees timestamps arrive in increasing order per key, simply appending each new entry preserves this invariant with no additional work.
Binary search on a sorted array identifies the exact boundary where elements transition from <= t to > t. The last element before this boundary is the maximum timestamp satisfying our condition.
Complexity
Let n_k denote the number of entries for a specific key, and N the total number of "set" operations.
- Time:
"set": O(1) amortized for hash lookup and list append"get": O(n_k) to extract timestamps + O(log n_k) for binary search = O(n_k)
- Space: O(N) to store all timestamp-value pairs
Note: Extracting timestamps into a new list on every query adds O(n_k) overhead. For production systems with frequent queries on keys with long histories, maintaining separate parallel lists for timestamps and values would reduce "get" to O(log n_k).
Solution
from bisect import bisect_right
from typing import List, Optional
def historical_store(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
store = {}
output = []
for op, args in zip(operations, arguments):
if op == "TimeMap":
store = {}
output.append(None)
elif op == "set":
key, value, timestamp = args
if key not in store:
store[key] = []
store[key].append((timestamp, value))
output.append(None)
elif op == "get":
key, timestamp = args
entries = store.get(key, [])
timestamps = [entry[0] for entry in entries]
idx = bisect_right(timestamps, timestamp) - 1
output.append(entries[idx][1] if idx >= 0 else "")
return output