Point-in-Time Lookups in a Versioned Key Store
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement a multi-version key-value store that retains every historical write for each key and answers point-in-time read queries over a sequential command log.
def run_time_store(operations: list[list]) -> list[str]:
Each element of operations takes one of two forms:
["set", key, value, timestamp]— appends a new revision mapping stringkeyto stringvalueat integertimestamp. Produces no output entry.["get", key, timestamp]— looks up stringkeyas of integertimestamp, returning thevaluefrom the previously processed"set"onkeywith the greatest write timestamp<= timestamp, or""if no qualifying write has occurred yet.
Behavioral guarantees:
- Commands execute sequentially from index
0onward, so a"get"only considers"set"commands that came earlier inoperations. - Across all
"set"commands in list order (spanning every key), write timestamps strictly increase; no two writes share the same timestamp. - Query timestamps in
"get"commands may take any integer value in the allowed range, whether earlier than, equal to, between, or later than existing writes. - Return one string per
"get"command in order of appearance, or[]ifoperationscontains no"get"commands.
Examples
Example 1
Input: operations = [["set", "plan", "free", 4], ["get", "plan", 2], ["get", "plan", 4], ["get", "plan", 6], ["set", "plan", "pro", 11], ["get", "plan", 10], ["get", "plan", 11], ["get", "plan", 25]]
Output: ["", "free", "free", "free", "pro", "pro"]
Querying "plan" at 2 finds no write at or before 2 and returns "". Queries at 4, 6, and 10 resolve to "free" (written at 4), whereas queries at 11 and 25 after the second write resolve to "pro" (written at 11).
Example 2
Input: operations = [["set", "host", "east", 5], ["set", "port", "8080", 9], ["get", "host", 9], ["get", "port", 6], ["get", "mode", 20]]
Output: ["east", "", ""]
"host" was set at 5 <= 9 ("east"), "port" was first set at 9 > 6 (""), and "mode" has no recorded revisions ("").
Example 3
Input: operations = [["set", "tag", "alpha", 12], ["get", "tag", 40], ["set", "tag", "beta", 25], ["get", "tag", 40], ["get", "tag", 18]]
Output: ["alpha", "beta", "alpha"]
During the first "get" at 40, only the write at 12 has executed, yielding "alpha". After "beta" is recorded at 25, querying at 40 returns "beta", while querying at 18 still returns "alpha" (12 <= 18 < 25).
Constraints
1 <= len(operations) <= 2 * 10^5- Every
keyandvalueis a non-empty string of1to20lowercase English letters (a–z) and digits (0–9). 1 <= timestamp <= 10^9
Step-by-step walkthrough
Understand the two time rules
This store never overwrites old values — every
"set"appends a timestamped revision of a key, and every"get"asks for a key's value as ofquery_time. Two rules work together:- Sequential visibility: a
"get"only observes"set"commands that came before it inoperations. You cannot load all"set"calls into memory first and answer"get"calls afterward. - Timestamp cutoff (
<=): among the already-processed"set"calls forkey, choose the one with the largest timestamp<= query_time, or""if none exists.
Example 3 timeline for key "tag": 1. ["set", "tag", "alpha", 12] -> history so far: [(12, "alpha")] 2. ["get", "tag", 40] -> latest <= 40 so far is 12 -> "alpha" 3. ["set", "tag", "beta", 25] -> history so far: [(12, "alpha"), (25, "beta")] 4. ["get", "tag", 40] -> latest <= 40 now is 25 -> "beta" 5. ["get", "tag", 18] -> latest <= 18 is still 12 -> "alpha"- Sequential visibility: a
Why linear scans and countdown loops are too slow
Two tempting approaches fail under the constraints (
len(operations) <= 200,000,timestamp <= 10^9):- Scanning all previous writes on every
get: if100,000writes to one key are followed by100,000reads, scanning the history takes100,000 * 100,000 = 10,000,000,000comparisons. - Stepping
query_timedown by1in a{timestamp: value}dictionary: a single query atquery_time = 10^9when the write occurred at1takes a billion loop iterations.
We need a way to record writes in
O(1)time and jump straight to the right historical version inO(log m)time (wheremis the number of versions recorded for that key).- Scanning all previous writes on every
Key idea: monotonic writes keep per-key lists sorted for free
Because write timestamps strictly increase across
operations, whenever we append a new(timestamp, value)forkey, its timestamp is automatically greater than every earlier timestamp forkey— so each key's timestamp list stays sorted in ascending order without ever callingsort().On a sorted list
key_times, finding the rightmost timestamp<= query_timeis a standard binary search (repeatedly halving the search range). Python'sbisect_right(key_times, query_time)returns the exact index wherequery_timewould be inserted after any equal timestamps — which equals the count of writes withwrite_time <= query_time:key_times = [ 4, 11 ] key_values = ["free", "pro"] indices: 0 1 query_time = 2 -> bisect_right gives 0 -> valid_count == 0 -> "" (no write <= 2) query_time = 4 -> bisect_right gives 1 -> key_values[1 - 1] = "free" query_time = 10 -> bisect_right gives 1 -> key_values[1 - 1] = "free" query_time = 11 -> bisect_right gives 2 -> key_values[2 - 1] = "pro"Why
bisect_rightand notbisect_left? Atquery_time = 11,bisect_left([4, 11], 11)returns1(counting only writes< 11), which would miss the exact-timestamp write"pro"and wrongly return"free".Code the binary search helper
Storing two parallel lists per key —
key_times: List[int]andkey_values: List[str]— letsbisect_rightcompare plain integers directly without building dummy tuple objects during queries.from bisect import bisect_right def latest_value_at_or_before( key_times: List[int], key_values: List[str], query_time: int ) -> str: """Return the value from the latest write with write_time <= query_time, or ''.""" # bisect_right returns how many timestamps in sorted `key_times` are <= query_time. # Using bisect_right (not bisect_left) includes a write at exact `query_time`. valid_count = bisect_right(key_times, query_time) if valid_count == 0: return "" return key_values[valid_count - 1]Code the sequential operation loop
Now we walk through
operationsonce in list order:- On
"set", initialize empty lists for an unseenkeyand appendtimestampandvalue. - On
"get", return""immediately ifkeyhas never been written yet; otherwise look up the answer withlatest_value_at_or_before.
def run_time_store(operations: list[list]) -> list[str]: # times_by_key: {key: [t1, t2, ...]} strictly increasing write timestamps per key times_by_key: Dict[str, List[int]] = {} # values_by_key: {key: [v1, v2, ...]} values aligned index-for-index with times_by_key[key] values_by_key: Dict[str, List[str]] = {} results: List[str] = [] # Process operations strictly in list order so a "get" never sees a later "set". for operation in operations: op_kind = operation[0] if op_kind == "set": key = operation[1] value = operation[2] timestamp = operation[3] if key not in times_by_key: times_by_key[key] = [] values_by_key[key] = [] # Global set timestamps strictly increase, so appending keeps times_by_key[key] sorted. times_by_key[key].append(timestamp) values_by_key[key].append(value) else: key = operation[1] query_time = operation[2] if key not in times_by_key: results.append("") else: answer = latest_value_at_or_before( times_by_key[key], values_by_key[key], query_time ) results.append(answer) return results- On
Trace Example 1 and review the complete solution
Let's verify every
"get"in Example 1 on key"plan":Operation times_by_key["plan"] valid_count Output --------------------------------------------------------------------------- ["set", "plan", "free", 4] [4] - - ["get", "plan", 2] [4] 0 "" ["get", "plan", 4] [4] 1 "free" ["get", "plan", 6] [4] 1 "free" ["set", "plan", "pro", 11] [4, 11] - - ["get", "plan", 10] [4, 11] 1 "free" ["get", "plan", 11] [4, 11] 2 "pro" ["get", "plan", 25] [4, 11] 2 "pro"The collected list
["", "free", "free", "free", "pro", "pro"]matches Example 1. Here is the complete solution:from typing import Any, Dict, List, Optional, Set, Tuple from bisect import bisect_right def latest_value_at_or_before( key_times: List[int], key_values: List[str], query_time: int ) -> str: """Return the value from the latest write with write_time <= query_time, or ''.""" # bisect_right returns how many timestamps in sorted `key_times` are <= query_time. # Using bisect_right (not bisect_left) includes a write at exact `query_time`. valid_count = bisect_right(key_times, query_time) if valid_count == 0: return "" return key_values[valid_count - 1] def run_time_store(operations: list[list]) -> list[str]: # times_by_key: {key: [t1, t2, ...]} strictly increasing write timestamps per key times_by_key: Dict[str, List[int]] = {} # values_by_key: {key: [v1, v2, ...]} values aligned index-for-index with times_by_key[key] values_by_key: Dict[str, List[str]] = {} results: List[str] = [] # Process operations strictly in list order so a "get" never sees a later "set". for operation in operations: op_kind = operation[0] if op_kind == "set": key = operation[1] value = operation[2] timestamp = operation[3] if key not in times_by_key: times_by_key[key] = [] values_by_key[key] = [] # Global set timestamps strictly increase, so appending keeps times_by_key[key] sorted. times_by_key[key].append(timestamp) values_by_key[key].append(value) else: key = operation[1] query_time = operation[2] if key not in times_by_key: results.append("") else: answer = latest_value_at_or_before( times_by_key[key], values_by_key[key], query_time ) results.append(answer) return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of a wiki page's revision log or an append-only accounting ledger: instead of overwriting yesterday's value when a key changes, every write adds a new dated line at the bottom of that key's log. That structure is a multi-version key-value store (a dictionary that preserves timestamped historical revisions of every key rather than only its latest value). Because "set" timestamps arrive in strictly ascending order across the command stream, each key's list of timestamps is already sorted from oldest to newest the moment we append to it. When a "get" asks what a key held at query_time, we run binary search (repeatedly halving the sorted list to eliminate half the remaining candidates at each step) via Python's bisect_right (an upper-bound binary search returning how many entries in a sorted list are <= query_time) and pick the entry right before that insertion index.
Why do simpler approaches fail? Scanning a key's entire history on every "get" takes O(m) time per read (m revisions), reaching 10^10 steps when 100,000 writes are followed by 100,000 reads on the same key. Stepping backward one unit at a time (query_time, query_time - 1, ...) in a hash map also fails because timestamps reach 10^9. Finally, loading all "set" commands before answering "get" commands is wrong because a "get" may only observe writes that appeared earlier in operations.
Here is a 5-command trace on key "tag" (Example 3):
1. ["set", "tag", "alpha", 12] -> times["tag"] = [12], values["tag"] = ["alpha"]
2. ["get", "tag", 40] -> bisect_right([12], 40) = 1 -> values["tag"][0] = "alpha"
3. ["set", "tag", "beta", 25] -> times["tag"] = [12, 25], values["tag"] = ["alpha", "beta"]
4. ["get", "tag", 40] -> bisect_right([12, 25], 40) = 2 -> values["tag"][1] = "beta"
5. ["get", "tag", 18] -> bisect_right([12, 25], 18) = 1 -> values["tag"][0] = "alpha"
Complexity
Let n be the total number of commands (len(operations)), s be the number of "set" calls, g be the number of "get" calls (s + g = n), and m <= s be the number of writes recorded for the queried key so far.
- Time:
O(1)amortized per"set",O(log m)per"get", andO(n + g log s)(O(n log n)) total. Each"set"performs a dictionary lookup and list.append(), running in amortizedO(1)time (constant time per append averaged across occasional list capacity doublings). Each"get"performs oneO(1)dictionary lookup plus a binary search overmsorted integers inO(log m)steps (at most ~17 comparisons even whenm = 100,000). - Space:
O(s)auxiliary space (plusO(g)for the returnedresultslist). Every"set"appends one integer totimes_by_keyand one string reference tovalues_by_key, storingsrevisions in total across all keys.
Edge cases
- Query on an unwritten key (
["get", "mode", 20]):key not in times_by_keyreturns""without allocating empty lists in the dictionary. - Query strictly earlier than a key's first write (
set @ 4,get @ 2):bisect_right([4], 2)returns0, sovalid_count == 0returns"". - Query on the exact write timestamp (
set @ 4,get @ 4):bisect_right([4], 4)returns1, returningkey_values[0]because the cutoff rule is<=, not<. - Query before a later write in list order (
get @ 40beforeset @ 25): Because we executeoperationssequentially,set @ 25is not intimes_by_keyyet during the firstget @ 40. - Zero
"get"commands:resultsstays[]and is returned directly. - Digit-only string keys or values (
"7","0"): Kept untouched asstrobjects without accidental integer conversion or truthiness bugs ("0"is returned rather than"").
Common mistakes
- Using
bisect_leftinstead ofbisect_right:bisect_left(key_times, query_time)counts only timestamps< query_time, so querying on an exact write timestamp misses that write and returns a stale value (or""). - Two-pass preprocessing (ingesting all
"set"commands before running"get"commands): Breaks sequential visibility — in Example 3, the first["get", "tag", 40]would prematurely observe["set", "tag", "beta", 25]and return"beta"instead of"alpha". - Searching tuples with
bisect_right(pairs, (query_time, "")): In Python,(11, "") < (11, "pro")because"" < "pro", sobisect_rightplaces(11, "")before(11, "pro")and misses the exact match. Separatetimes_by_keyandvalues_by_keylists avoid tuple tie-breaker bugs completely. - Returning
Noneinstead of""on misses: The signature requires an empty string""whenever no qualifying write exists.
Alternative approaches
- Hand-written binary search (
lo,hiloop): Trackbest_idx = -1while halvinglo..hi: whenkey_times[mid] <= query_time, setbest_idx = midandlo = mid + 1; otherwise sethi = mid - 1. Runs in the sameO(log m)time andO(s)space without relying on standard-library bisect helpers. - Single list of
(timestamp, value)tuples withchr(127)sentinel: Works if you search with(query_time, chr(127))since ASCII127sorts after all lowercase letters and digits, though parallel lists are cleaner and faster.
Follow-up questions
- What changes if write timestamps can arrive out of chronological order? Appending to a plain Python list would no longer keep
times_by_key[key]sorted, and inserting in the middle viabisect.insortshifts elements inO(m)time per write. To maintainO(log m)time for both out-of-order writes and historical reads, store each key's revisions in a balanced search tree (a self-balancing binary tree such as a red-black tree, C++std::map, JavaTreeMap, or Python'ssortedcontainers.SortedDict), and clarify the tie-breaking policy when two writes to the same key carry identical timestamps (such as last-arrival-wins overwrite). - How would you support range queries returning every (timestamp, value) revision of a key within [t_start, t_end]? Perform two binary searches on
times_by_key[key]:start_idx = bisect_left(key_times, t_start)locates the first write>= t_start, andend_idx = bisect_right(key_times, t_end)locates the slice boundary just past the last write<= t_end. Slicingzip(key_times[start_idx:end_idx], key_values[start_idx:end_idx])runs inO(log m + k)time, wherekis the number of returned revisions. - How would you bound memory consumption in a continuously running production store? Enforce a retention watermark (a cutoff timestamp such as
now - 7 daysbelow which historical point-in-time reads are rejected) paired with background compaction (garbage collection of superseded revisions). Crucially, compaction must retain the single newest revision at or before the watermark for each key — purging every entry older than the watermark would accidentally erase keys written 10 days ago and never updated since.
Follow-up questions
- What changes if write timestamps can arrive out of chronological order?
- How would you support range queries returning every (timestamp, value) revision of a key within [t_start, t_end]?
- How would you bound memory consumption in a continuously running production store?
Similar questions
- Increment Fixed-Size Digit Array by One
- Square Root Approximation Without Built-In Exponents
- Validate Nesting of Three Bracket Types
- Distinct Phrase Variations via Anagram Substitution
- Count Enclosed Islands
- Interior Land Islands in a Binary Matrix
More Oracle interview questions
- Optimal Gain from a Single Share Transaction Medium
- System Architecture Walkthrough: End-to-End Topology, Trade-Offs, and Business Value Medium
- Total Island Count and Maximum Island Area Medium Pro
- Distributed L4/L7 Load Balancer Medium Pro
- All Lexicographical Down-Right Routes in an Obstacle Grid Medium Pro
- Fixed-TTL Key-Value Store with Renewal and Active Count Easy Pro
- Maximum Rating Sum Without Consecutive Skips Medium Pro
- Largest Minimum Across Fixed-Length Subarrays Medium Pro
- Fewest Rooms for Concurrent Meetings Medium Pro
- Object-Oriented Fixed-Capacity LRU Cache in Constant Time Medium Pro