Historical Key-Value Lookups by Timestamp
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory multi-version key-value store that preserves the complete write history of every key and answers historical point-in-time lookups efficiently.
Implement the driver function:
def run_versioned_store(operations: list[tuple]) -> list[str]:
The input operations is an ordered sequence of commands. Each element takes one of two forms:
("set", key, value, timestamp)— Append a new version recordingvalueforkeyat integer timetimestampwhile retaining all previously stored versions ofkey.("get", key, timestamp)— Query the value associated withkeyas of integer timetimestamp.
Process operations strictly from left to right and enforce these lookup semantics:
- Sequential visibility: A
"get"operation may only inspect"set"operations for the samekeythat appear earlier inoperations. Writes appearing later inoperationsare invisible to earlier reads regardless of their timestamps. - Timestamp selection: Among visible writes for
key, return thevaluebelonging to the write with the largest timestamp less than or equal to the"get"timestamp. - Missing or future-only history: If
keyhas no prior writes, or if every prior write tokeyoccurred strictly after the"get"timestamp, return"". - Output format: Collect and return one string per
"get"operation in the order those queries occur. Ifoperationscontains zero"get"entries, return[].
Your per-key storage layout should support sublinear point-in-time queries rather than scanning all recorded versions on every read.
Examples
Example 1
Input: operations = [
("set", "mode", "eco", 3),
("get", "mode", 2),
("get", "mode", 3),
("set", "mode", "turbo", 10),
("get", "mode", 7),
("get", "mode", 10),
("get", "mode", 25),
]
Output: ["", "eco", "eco", "turbo", "turbo"]
Explanation:
- Querying "mode" at time 2 finds no write at or before 2 (the earliest write is at 3), returning "".
- Queries at times 3 and 7 both resolve to "eco" written at 3, since "turbo" is recorded at 10 > 7.
- Queries at times 10 and 25 both resolve to "turbo" written at 10.
Example 2
Input: operations = [
("set", "host", "n1", 2),
("get", "host", 50),
("set", "port", "8080", 4),
("get", "port", 3),
("set", "host", "n2", 8),
("get", "host", 50),
("get", "region", 10),
]
Output: ["n1", "", "n2", ""]
Explanation:
- The first ("get", "host", 50) runs before ("set", "host", "n2", 8) is processed, so only "n1" (at 2) exists and "n1" is returned.
- ("get", "port", 3) precedes "port"'s earliest timestamp 4, returning "".
- After "host" is updated to "n2" at time 8, the second ("get", "host", 50) returns "n2".
- "region" is never written, so ("get", "region", 10) returns "".
Constraints
1 <= len(operations) <= 2 * 10^5- Each
keyandvalueconsists of1to100lowercase ASCII letters (a–z) and digits (0–9). 1 <= timestamp <= 10^7across all"set"and"get"commands.- Across all
"set"operations inoperations(spanning all keys), timestamps are strictly increasing in list order. - Timestamps on
"get"operations may appear in any order within[1, 10^7].
Step-by-step walkthrough
Understand historical lookups and the two visibility rules
Rather than overwriting entries in place, our store retains every timestamped version written to each key:
("set", key, value, timestamp)appends a version ofkeystamped attimestamp.("get", key, query_time)looks up the versionkeyheld as ofquery_time.
Here is Example 1 plotted along a timeline for
"mode":Timeline for "mode": time: 1 2 3 7 10 25 writes: [ "eco" @3 ] [ "turbo" @10 ] reads: ^ ^ ^ ^ ^ @2 @3 @7 @10 @25 result: "" "eco" "eco" "turbo" "turbo"Every
"get"enforces two visibility rules simultaneously:- Timestamp rule (
<= query_time): Among visible writes tokey, pick the one with the largesttimestamp <= query_time(or""if none qualifies). - List-order rule (earlier in
operations): Only"set"commands appearing before this"get"inoperationsare visible, even whenquery_timelies far in the future.
Why scanning versions is too slow
A straightforward brute force keeps a list of
(timestamp, value)pairs per key and scans that list on every"get"to locate the largest timestamp<= query_time.With up to
200,000operations, imagine100,000"set"writes to one popular key"hot", followed by100,000"get"queries asking about early timestamps:- Scanning forward inspects up to
100,000versions per read. - Scanning backward from newest to oldest still walks nearly all
100,000versions wheneverquery_timesits near the beginning of history.
Either linear scan performs roughly
100,000 * 100,000 = 10^10comparisons and times out. Reads needO(log V)time overVversions rather thanO(V).- Scanning forward inspects up to
Key idea: append-only sorted lists + binary search
Notice the monotonic constraint on writes: write timestamps strictly increase in the order
"set"commands appear.That single property gives us two advantages immediately:
- Replaying
operationssequentially guarantees that whenever a"get"executes, the store contains only"set"commands that appeared earlier inoperations. - Every newly appended write timestamp for a key exceeds all prior timestamps for that key — so each key's timestamp list stays sorted in ascending order without ever calling
sort()!
On a sorted list
key_times, all timestamps<= query_timeform a contiguous prefix on the left, while timestamps> query_timesit on the right. Python'sbisect_right(key_times, query_time)runs binary search to find that split indexvalid_countinO(log V)comparisons:Suppose key_times = [ 3, 10, 18, 24 ] key_values = ["eco", "turbo", "race", "idle"] indices = 0 1 2 3 Query with query_time = 10: <= 10 | > 10 [ 3, 10 ] | [ 18, 24 ] ^ split index valid_count = 2 valid_count - 1 = index 1 -> key_times[1] = 10, key_values[1] = "turbo"Why choose
bisect_rightoverbisect_left?bisect_left([3, 10, 18, 24], 10)returns1(the count of timestamps strictly< 10), skipping the version written at exact time10!bisect_right([3, 10, 18, 24], 10)returns2(the count of timestamps<= 10). Whenevervalid_count == 0, no timestamp satisfies<= query_timeso we return""; otherwisevalid_count - 1points to the latest qualifying version.
- Replaying
Build the store: O(1) versioned writes
We encapsulate the state inside
VersionedStoreusing two parallel dictionaries keyed bykey:self.times[key]: sorted list of integer timestamps, e.g.[3, 10].self.values[key]: parallel list of string values at matching indices, e.g.["eco", "turbo"].
Keeping timestamps in a dedicated
List[int]letsbisect_rightcompare plain integers directly rather than unpacking(timestamp, value)tuples.from typing import Dict, List class VersionedStore: """In-memory multi-version key-value store supporting point-in-time reads.""" def __init__(self) -> None: # times: maps key -> strictly increasing list of write timestamps, e.g. {"mode": [3, 10]} self.times: Dict[str, List[int]] = {} # values: maps key -> parallel list of values at matching indices, e.g. {"mode": ["eco", "turbo"]} self.values: Dict[str, List[str]] = {} def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.times: self.times[key] = [] self.values[key] = [] # Set timestamps strictly increase across the operation stream, so appending # keeps self.times[key] sorted in O(1) amortized time with no sorting step. self.times[key].append(timestamp) self.values[key].append(value)Add O(log V) point-in-time reads
Inside
get(self, key, query_time):- If
keyhas no recorded writes (key not in self.times), return"". - Compute
valid_count = bisect_right(self.times[key], query_time). - If
valid_count == 0, every recorded write happened strictly afterquery_time, so return"". - Otherwise return
self.values[key][valid_count - 1].
from bisect import bisect_right def get(self, key: str, query_time: int) -> str: if key not in self.times: return "" key_times = self.times[key] # bisect_right counts how many recorded timestamps are <= query_time # (bisect_left would count < query_time and miss an exact timestamp match). valid_count = bisect_right(key_times, query_time) if valid_count == 0: # Every version recorded so far was written strictly after query_time. return "" # Index valid_count - 1 holds the rightmost (largest) timestamp <= query_time. return self.values[key][valid_count - 1]- If
Trace Example 1 and Example 2's list-order rule
First, step through Example 1 command by command:
1. ("set", "mode", "eco", 3) -> times["mode"] = [3], values["mode"] = ["eco"] 2. ("get", "mode", 2) -> bisect_right([3], 2) = 0 -> "" 3. ("get", "mode", 3) -> bisect_right([3], 3) = 1 -> values[0] = "eco" 4. ("set", "mode", "turbo", 10) -> times["mode"] = [3, 10], values["mode"] = ["eco", "turbo"] 5. ("get", "mode", 7) -> bisect_right([3, 10], 7) = 1 -> values[0] = "eco" 6. ("get", "mode", 10) -> bisect_right([3, 10], 10) = 2 -> values[1] = "turbo" 7. ("get", "mode", 25) -> bisect_right([3, 10], 25) = 2 -> values[1] = "turbo" Returned list: ["", "eco", "eco", "turbo", "turbo"]Now trace
"host"across Example 2 to verify sequential visibility:1. ("set", "host", "n1", 2) -> times["host"] = [2], values["host"] = ["n1"] 2. ("get", "host", 50) -> times["host"] only holds [2] right now -> returns "n1" (not "n2"!) 5. ("set", "host", "n2", 8) -> times["host"] = [2, 8], values["host"] = ["n1", "n2"] 6. ("get", "host", 50) -> bisect_right([2, 8], 50) = 2 -> returns "n2"Because
operationsis replayed in a single pass, an earlier"get"never observes a later"set".Complete solution
Here is the complete
VersionedStoreclass andrun_versioned_storedriver:from bisect import bisect_right from typing import Any, Dict, List, Optional, Set, Tuple class VersionedStore: """In-memory multi-version key-value store supporting point-in-time reads.""" def __init__(self) -> None: # times: maps key -> strictly increasing list of write timestamps, e.g. {"mode": [3, 10]} self.times: Dict[str, List[int]] = {} # values: maps key -> parallel list of values at matching indices, e.g. {"mode": ["eco", "turbo"]} self.values: Dict[str, List[str]] = {} def set(self, key: str, value: str, timestamp: int) -> None: if key not in self.times: self.times[key] = [] self.values[key] = [] # Set timestamps strictly increase across the operation stream, so appending # keeps self.times[key] sorted in O(1) amortized time with no sorting step. self.times[key].append(timestamp) self.values[key].append(value) def get(self, key: str, query_time: int) -> str: if key not in self.times: return "" key_times = self.times[key] # bisect_right counts how many recorded timestamps are <= query_time # (bisect_left would count < query_time and miss an exact timestamp match). valid_count = bisect_right(key_times, query_time) if valid_count == 0: # Every version recorded so far was written strictly after query_time. return "" # Index valid_count - 1 holds the rightmost (largest) timestamp <= query_time. return self.values[key][valid_count - 1] def run_versioned_store(operations: list[tuple]) -> list[str]: store = VersionedStore() results: List[str] = [] # Process operations strictly in list order so a "get" never sees a later "set". for op in operations: op_type = op[0] if op_type == "set": key, value, timestamp = op[1], op[2], op[3] store.set(key, value, timestamp) elif op_type == "get": key, query_time = op[1], op[2] results.append(store.get(key, query_time)) else: raise ValueError(f"unknown operation: {op_type!r}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of each key in the store as an item on an append-only ledger sheet where old lines are never erased — every "set" adds a new line stamped with its write time, and every "get" asks, "Looking only at lines recorded so far, what was the latest entry on this key's sheet at or before minute T?"
A plain dictionary (store[key] = value) fails because overwriting forgets historical states, while storing a version list per key and scanning it on every read takes O(V) time for V versions — 100,000 writes to one hot key followed by 100,000 reads targeting early timestamps would perform roughly 10^10 checks. Because "set" timestamps strictly increase in list order, appending to a key's timestamp list keeps it automatically sorted, allowing binary search (repeatedly halving a sorted array to locate a boundary in logarithmic time) to jump straight to the right version.
Walk through ("set", "mode", "eco", 3), ("set", "mode", "turbo", 10), ("get", "mode", 2), ("get", "mode", 7), ("get", "mode", 10):
1. After both writes, times["mode"] = [3, 10] and values["mode"] = ["eco", "turbo"].
2. At query_time = 2, bisect_right([3, 10], 2) finds 0 timestamps <= 2, returning "".
3. At query_time = 7, bisect_right([3, 10], 7) finds 1 timestamp <= 7, so index 1 - 1 = 0 returns "eco".
4. At query_time = 10, bisect_right([3, 10], 10) finds 2 timestamps <= 10, so index 2 - 1 = 1 returns "turbo".
Complexity
Let N be len(operations), S be the number of "set" commands, and G be the number of "get" commands (S + G = N). Keys have bounded length (<= 100 characters), so hashing a key takes O(1) time.
- Time: O(S + G log S), which is O(N log N) in the worst case. Each
"set"performs anO(1)average-time dictionary lookup and two amortized O(1) list appends (meaningO(1)per append on average across dynamic array resizes). Each"get"performs anO(1)dictionary lookup and onebisect_rightbinary search over at mostStimestamps for that key inO(log S)time. - Space: O(S + G) to store the
Shistorical(timestamp, value)entries across all keys plus theGoutput strings inresults.
Edge cases
- Key never written:
key not in self.timesimmediately returns"". - Query timestamp earlier than the key's first write:
bisect_rightreturns0, cleanly yielding"". - Query timestamp equal to a write timestamp: Included by
<=, which is why we usebisect_rightrather thanbisect_left. - Future query timestamp before a later write in
operations: Replayingoperationssequentially means("get", "host", 50)before("set", "host", "n2", 8)cannot see"n2", whereas repeating("get", "host", 50)afterward returns"n2". - Identical value written multiple times: Stored as distinct timestamped entries without affecting intermediate reads.
- No
"get"commands at all: Returns[].
Common mistakes
- Using
bisect_leftinstead ofbisect_right:bisect_left([3, 10], 3)returns0, missing a version written at exact timestamp3. - Loading all
"set"commands in pass 1 and answering"get"commands in pass 2: Breaks sequential visibility because earlier reads would see future writes inoperations. - Linearly scanning backward from the newest version: Fast for recent queries, but degrades to
O(V)per read when queries target the start of a key's history. - Calling
.sort()ontimes[key]during writes or reads: WastesO(V log V)work per step because strictly increasing"set"timestamps keeptimes[key]sorted on append. - Returning
Noneinstead of""when no qualifying version exists.
Alternative approaches
- Hand-rolled binary search loop (useful if an interviewer asks you not to use
bisect): Maintain an inclusive range[lo, hi]and updateans = midwheneverkey_times[mid] <= query_time:
lo, hi = 0, len(key_times) - 1
ans = -1
while lo <= hi:
mid = (lo + hi) // 2
if key_times[mid] <= query_time:
ans = mid
lo = mid + 1 # search right for an even newer qualifying timestamp
else:
hi = mid - 1 # mid is too late; search left
return "" if ans == -1 else key_values[ans]
- Single list of
(timestamp, value)tuples per key: In Python 3.10+,bisect_right(versions, query_time, key=...)searches pairs directly; paralleltimesandvalueslists avoid invoking a Python key callback at each probe.
Follow-up questions
- How would your per-key data structure change if write timestamps were allowed to arrive out of chronological order? Plain list appends would no longer keep
times[key]sorted, and inserting into the middle of a Python list viabisect.insortshifts elements inO(V)time per write. To keep both writes and historical reads inO(log V)time, store each key's versions in a balanced binary search tree or a skip list (a randomized multi-level linked list supportingO(log V)search and insertion), and define a tie-breaking rule (such as "later operation wins") if two writes to the same key carry identical timestamps. - How can a long-running storage engine reclaim old versions without breaking historical queries within a retention window? Enforce a garbage-collection cutoff
T_gc = now - retention_window: for each key, any version strictly older thanT_gccan be discarded except the single newest version at or beforeT_gc, which is still required to answer queries atT_gc. Any query withquery_time < T_gcshould raise a retention-expired error rather than returning"", and compacting expired prefixes from sorted version lists reclaims space in amortizedO(1)time per version. - How do production MVCC databases ensure that repeating a historical read at timestamp T always returns the exact same result? In our single-stream specification,
get("host", 50)at time2returns"n1"and a subsequentset("host", "n2", 8)changes whatget("host", 50)returns later. Distributed databases using MVCC (Multi-Version Concurrency Control) (a concurrency model serving reads from immutable timestamped versions without blocking writers) prevent retroactive changes either by tracking a read-timestamp cache per key range and pushing any conflicting write to a timestamp strictly aboveT, or by serving lock-free historical reads only atT <= closed_timestamponce the cluster guarantees no future write can commit at or belowT.
Follow-up questions
- How would your per-key data structure change if write timestamps were allowed to arrive out of chronological order?
- How can a long-running storage engine reclaim old versions without breaking historical queries within a retention window?
- How do production MVCC databases ensure that repeating a historical read at timestamp T always returns the exact same result?
Similar questions
- Architecture Walkthrough and Defense of a System You Led
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One