Snapshot Reads from a Multi-Version Key-Value Log
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests whether you can design a versioned key-value store that answers "what was the value at time T?" in sub-linear time using binary search on per-key version histories.
You are building a simple multi-version data store. Every write is recorded permanently alongside its timestamp, and reads ask for the state of a key at a particular point in time. Nothing is ever overwritten or deleted.
The store is driven by a sequence of operations processed from first to last. Your function receives the full list and returns one result per read operation, in the order the reads appear.
Operations
Each operation is a tuple in one of these two forms:
("set", key, value, timestamp)— recordvalueforkeyat timetimestamp. Earlier versions ofkeyare kept.("get", key, timestamp)— look upkeyas of timetimestamp.
Read Rules
A get for key at time timestamp considers only the set operations for that same key that appear earlier in the operation list. Among those, it returns the value whose timestamp is the largest one that does not exceed timestamp.
If no qualifying version exists (the key has never been written, or every prior write for that key has a timestamp strictly greater than timestamp), return the empty string "".
Constraints
1 <= len(operations) <= 2 * 10^5- Every
keyandvalueis a non-empty string of at most 100 lowercase alphanumeric characters. 1 <= timestamp <= 10^7for every operation.- The timestamps of
setoperations strictly increase in the order they appear across the entire operation list (regardless of key). Timestamps ofgetoperations may appear in any order. - Return a list containing one string per
getoperation, in the order thosegets appear. Return an empty list if there are nogetoperations.
Examples
Example 1
Input: run_versioned_store([['set', 'price', '10', 5], ['get', 'price', 4], ['get', 'price', 5], ['set', 'price', '12', 9], ['get', 'price', 8], ['get', 'price', 9], ['get', 'price', 100]])
Output: ['', '10', '10', '12', '12']
Example 2
Input: run_versioned_store([['set', 'a', 'x', 1], ['set', 'b', 'y', 2], ['get', 'a', 2], ['get', 'b', 1], ['set', 'a', 'z', 3], ['get', 'a', 3], ['get', 'c', 3]])
Output: ['x', '', 'z', '']
Hints
Hint 1
For each key, think about what data structure lets you answer 'largest timestamp ≤ T' without scanning every version. A sorted sequence supports this with binary search.
Hint 2
The global guarantee that set timestamps strictly increase across the whole operation list has a useful consequence: when you append a new version to any key's history, that list is always already in sorted order.
Hint 3
Python's bisect module has two variants — bisect_left and bisect_right. Think carefully about which one correctly includes the case where the get timestamp exactly matches a stored timestamp, and what to do when the returned index is 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is answering "largest write timestamp ≤ T" efficiently. A naive scan through every version of a key would be O(versions), which in the worst case makes the whole workload O(n²) — too slow at n = 2 × 10⁵.
The key insight is to keep each key's version history as a sorted list of timestamps with a parallel list of values, and answer every read with binary search.
Why the lists stay sorted automatically
The problem guarantees that set timestamps strictly increase across the entire operation list. That monotonicity carries over to each individual key: whenever a new version of key K is written, its timestamp is larger than every timestamp already stored for K, so a simple append keeps the list sorted. No re-sorting or middle insertion is ever needed.
Binary search for the predecessor
Given a sorted list t of timestamps and a query time ts, we want the rightmost position where t[i] <= ts. Python's bisect_right(t, ts) returns the number of elements in t that are <= ts — equivalently, the index just past the last qualifying version.
- If that index is
0, no version existed at or beforets, so return"". - Otherwise, the answer is
vals[key][i - 1].
Using bisect_right (not bisect_left) is intentional: it places the query after any element that equals ts, so index i - 1 points at an exact-match version rather than skipping it.
Correctness
- Operations are processed in order, so when a
getruns, the version lists contain exactly thesets that precede it in the input — which is what the rules require. - The sorted invariant holds by the monotonic-timestamp argument above.
bisect_rightfinds the unique predecessor boundary in O(log k) where k is the number of versions for that key.- No
setremoves or overwrites old entries, so reads with small timestamps always find older versions correctly.
Edge cases
- Key never written:
times.get(key)returnsNone; return"". - Read before the first write for a key:
bisect_rightreturns0; return"". - Read timestamp exactly matches a write timestamp:
bisect_rightplaces the index after the equal element, soi - 1correctly points to it. - Read timestamp far in the future:
i == len(t), soi - 1is the last (most recent) version. - No
getoperations:outis never appended to, so[]is returned.
Complexity
Let n = total number of operations and k = number of versions of the key being queried.
set: O(1) amortised — one dict lookup and two appends.get: O(log k) forbisect_right, O(1) for the dict lookup.- Overall: O(n log n) worst case (e.g. all writes target one key, then many reads follow). A linear scan per read would be O(n²) ≈ 4 × 10¹⁰ operations at the constraint limit.
- Space: O(n) — every version is stored once; the result list holds at most n strings.
Full solution
from bisect import bisect_right
from typing import List, Tuple
def run_versioned_store(operations: List[Tuple]) -> List[str]:
# times[key]: strictly increasing list of write timestamps for that key
# vals[key]: parallel list of values at each timestamp
times = {}
vals = {}
out = []
for op in operations:
if op[0] == "set":
_, key, value, ts = op
# Because global set timestamps strictly increase, appending
# always maintains each key's list in sorted order.
times.setdefault(key, []).append(ts)
vals.setdefault(key, []).append(value)
else:
_, key, ts = op
t = times.get(key)
if not t:
# Key has never been written.
out.append("")
continue
# bisect_right returns the number of timestamps <= ts.
# The version we want is at index i-1 (if i > 0).
i = bisect_right(t, ts)
out.append(vals[key][i - 1] if i else "")
return out
Follow-up considerations
- Unordered writes: if
settimestamps could arrive out of order, you would need to insert into the sorted list rather than append.bisect.insortkeeps the list sorted but shifts elements, making each insert O(k). For true O(log k) inserts and lookups you would reach for a balanced BST —sortedcontainers.SortedListin Python or aTreeMapin Java. - Duplicate write timestamps: the constraints rule this out, but if they were allowed you would need a tie-breaking rule (e.g. last write wins, or a sequence number as a secondary sort key).
- Memory management: production multi-version stores (like CockroachDB's MVCC layer) periodically garbage-collect versions older than a configurable retention horizon, since no permitted read can reach them.