Versioned Key-Value Log with Point-in-Time Reads
Data Structure DesignAuto-graded · 23 test casesLast updated
Tests per-key version tracking and efficient predecessor search to retrieve the most recent value written at or before any queried timestamp.
Versioned Key-Value Log with Point-in-Time Reads
You are building a simple versioned data store. Every write records a string value under a string key at a specific integer timestamp. Reads ask for a snapshot view: given a key and a point in time, what was the most recently written value for that key at or before that moment?
Implement a function that processes a mixed sequence of write and read operations in order and returns the answer to every read.
Operations
Each element of the input list is one of two forms:
["set", key, value, timestamp]— storesvalueunderkeyattimestamp. Produces no output.["get", key, timestamp]— retrieves the value associated withkeyfrom the write whose timestamp is the largest one that does not exceedtimestamp. If no such write exists, produces"".
key and value are strings; timestamp is a positive integer.
Rules
- Operations are executed strictly in list order. A
getcan only observesetoperations that precede it in the list. - Across all
setoperations in the entire list, timestamps are strictly increasing. No two writes (even to different keys) share a timestamp. - A
gettimestamp can fall anywhere in the allowed range — before all writes to that key, between writes, exactly on a write, or after all writes. - The return value is a list containing one string per
get, in the order thosegets appear. If the input contains nogetoperations, return an empty list.
Constraints
1 <= len(operations) <= 2 * 10^5- Every
keyandvalueis a non-empty string of at most 20 lowercase English letters and digits. 1 <= timestamp <= 10^9- Write timestamps are strictly increasing across the full operation list.
Examples
Example 1
Input: replay_versioned_store([['set', 'color', 'red', 3], ['get', 'color', 2], ['get', 'color', 3], ['get', 'color', 5], ['set', 'color', 'blue', 8], ['get', 'color', 7], ['get', 'color', 8], ['get', 'color', 100]])
Output: ['', 'red', 'red', 'red', 'blue', 'blue']
Example 2
Input: replay_versioned_store([['set', 'a', 'x', 1], ['set', 'b', 'y', 2], ['get', 'a', 2], ['get', 'b', 1], ['get', 'c', 5]])
Output: ['x', '', '']
Example 3
Input: replay_versioned_store([['set', 'k', 'v1', 10], ['get', 'k', 50], ['set', 'k', 'v2', 20], ['get', 'k', 50], ['get', 'k', 15]])
Output: ['v1', 'v2', 'v1']
Hints
Hint 1
For each key separately, think about what structure naturally holds all of its write timestamps in sorted order — and consider whether you even need to sort explicitly given the global ordering guarantee on writes.
Hint 2
Once you have a sorted list of timestamps for a key, a get is asking for the rightmost timestamp that does not exceed the query value. That is a classic predecessor search, which binary search handles in O(log n).
Hint 3
Be careful about which bisect variant you choose. A get at exactly a write's timestamp should return that write's value, so make sure your index arithmetic lands on the equal element rather than the one before it.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observations
Per-key timestamp lists are sorted for free. The problem guarantees that set timestamps are strictly increasing across the entire operation list. Any subsequence of that list — such as all writes to a single key — therefore also increases strictly. Appending each new write to a per-key list is enough to keep it sorted; no insertion sort or balanced tree is needed.
A get is a predecessor query. Given a sorted list of timestamps for a key, finding the latest write at or before time t is exactly "find the rightmost element ≤ t", a textbook binary search.
Algorithm
Maintain two dictionaries keyed by the store key:
times[key]— timestamps of every set to that key, appended in arrival order.vals[key]— the corresponding values, parallel totimes[key].
For each operation in order:
- Set: append the timestamp and value to the key's lists. O(1) amortised.
- Get: look up the key's timestamp list. If it is absent the key was never written — output
"". Otherwise callbisect_right(times[key], query_ts), which returns the count of stored timestamps that are ≤query_ts(call itidx). Ifidx == 0, every write came after the query time — output"". Otherwise outputvals[key][idx - 1], the value of the latest qualifying write.
Why bisect_right and not bisect_left
bisect_right(list, t) places the split point after any element equal to t, so idx - 1 lands on a write timestamped exactly at t. Using bisect_left instead would place the split before the equal element, pushing idx - 1 to the write before it — an off-by-one error for exact-match queries.
Correctness
Sortedness invariant: after processing any prefix of the operations, each times[key] contains the timestamps of the sets seen so far in strictly increasing order. This holds at the start (empty) and is preserved by appending, since each new set's timestamp is larger than all previous writes globally.
Visibility: operations are processed sequentially with no look-ahead, so a get only observes sets that appeared earlier in the list.
Predecessor correctness: bisect_right(t, ts) - 1 is precisely the index of the largest timestamp ≤ ts when idx > 0, which is the write the problem asks for.
Edge cases
- Key never written →
times.get(key)returnsNone, output"". - Query earlier than the key's first write →
bisect_rightreturns 0, output"". - Query exactly on a write timestamp →
bisect_rightcounts it,idx - 1lands on it. - Query far in the future →
idx = len(list), returns the last written value. - A get appears before any write for that key even though later writes exist → sequential processing ensures those later writes are not yet in the list.
- No gets at all →
outstays empty, return[].
Complexity
| Cost | |
|---|---|
| Each set | O(1) amortised (dict lookup + list append) |
| Each get | O(log k) where k is the number of writes to that key |
| Overall | O(n log n) worst case |
| Space | O(S) where S is the total number of set operations |
String keys of at most 20 characters hash in effectively constant time.
Full solution
from bisect import bisect_right
from typing import List
def replay_versioned_store(operations: List[List]) -> List[str]:
times = {} # key -> sorted list of write timestamps (sorted by construction)
vals = {} # key -> parallel list of written values
out = []
for op in operations:
if op[0] == "set":
_, key, value, ts = op
if key in times:
times[key].append(ts)
vals[key].append(value)
else:
times[key] = [ts]
vals[key] = [value]
else: # "get"
_, key, ts = op
t = times.get(key)
if not t:
out.append("") # key has never been written
continue
idx = bisect_right(t, ts) # number of writes with timestamp <= ts
out.append(vals[key][idx - 1] if idx else "")
return out