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 string key to string value at integer timestamp. Produces no output entry.
  • ["get", key, timestamp] — looks up string key as of integer timestamp, returning the value from the previously processed "set" on key with the greatest write timestamp <= timestamp, or "" if no qualifying write has occurred yet.

Behavioral guarantees:

  • Commands execute sequentially from index 0 onward, so a "get" only considers "set" commands that came earlier in operations.
  • 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 [] if operations contains 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 key and value is a non-empty string of 1 to 20 lowercase English letters (a–z) and digits (0–9).
  • 1 <= timestamp <= 10^9

Step-by-step walkthrough

  1. 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 of query_time. Two rules work together:

    1. Sequential visibility: a "get" only observes "set" commands that came before it in operations. You cannot load all "set" calls into memory first and answer "get" calls afterward.
    2. Timestamp cutoff (<=): among the already-processed "set" calls for key, 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"
    
  2. 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: if 100,000 writes to one key are followed by 100,000 reads, scanning the history takes 100,000 * 100,000 = 10,000,000,000 comparisons.
    • Stepping query_time down by 1 in a {timestamp: value} dictionary: a single query at query_time = 10^9 when the write occurred at 1 takes a billion loop iterations.

    We need a way to record writes in O(1) time and jump straight to the right historical version in O(log m) time (where m is the number of versions recorded for that key).

  3. 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) for key, its timestamp is automatically greater than every earlier timestamp for key — so each key's timestamp list stays sorted in ascending order without ever calling sort().

    On a sorted list key_times, finding the rightmost timestamp <= query_time is a standard binary search (repeatedly halving the search range). Python's bisect_right(key_times, query_time) returns the exact index where query_time would be inserted after any equal timestamps — which equals the count of writes with write_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_right and not bisect_left? At query_time = 11, bisect_left([4, 11], 11) returns 1 (counting only writes < 11), which would miss the exact-timestamp write "pro" and wrongly return "free".

  4. Code the binary search helper

    Storing two parallel lists per key — key_times: List[int] and key_values: List[str] — lets bisect_right compare 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]
    
  5. Code the sequential operation loop

    Now we walk through operations once in list order:

    • On "set", initialize empty lists for an unseen key and append timestamp and value.
    • On "get", return "" immediately if key has never been written yet; otherwise look up the answer with latest_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
    
  6. 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", and O(n + g log s) (O(n log n)) total. Each "set" performs a dictionary lookup and list .append(), running in amortized O(1) time (constant time per append averaged across occasional list capacity doublings). Each "get" performs one O(1) dictionary lookup plus a binary search over m sorted integers in O(log m) steps (at most ~17 comparisons even when m = 100,000).
  • Space: O(s) auxiliary space (plus O(g) for the returned results list). Every "set" appends one integer to times_by_key and one string reference to values_by_key, storing s revisions in total across all keys.

Edge cases

  • Query on an unwritten key (["get", "mode", 20]): key not in times_by_key returns "" without allocating empty lists in the dictionary.
  • Query strictly earlier than a key's first write (set @ 4, get @ 2): bisect_right([4], 2) returns 0, so valid_count == 0 returns "".
  • Query on the exact write timestamp (set @ 4, get @ 4): bisect_right([4], 4) returns 1, returning key_values[0] because the cutoff rule is <=, not <.
  • Query before a later write in list order (get @ 40 before set @ 25): Because we execute operations sequentially, set @ 25 is not in times_by_key yet during the first get @ 40.
  • Zero "get" commands: results stays [] and is returned directly.
  • Digit-only string keys or values ("7", "0"): Kept untouched as str objects without accidental integer conversion or truthiness bugs ("0" is returned rather than "").

Common mistakes

  • Using bisect_left instead of bisect_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", so bisect_right places (11, "") before (11, "pro") and misses the exact match. Separate times_by_key and values_by_key lists avoid tuple tie-breaker bugs completely.
  • Returning None instead of "" on misses: The signature requires an empty string "" whenever no qualifying write exists.

Alternative approaches

  • Hand-written binary search (lo, hi loop): Track best_idx = -1 while halving lo..hi: when key_times[mid] <= query_time, set best_idx = mid and lo = mid + 1; otherwise set hi = mid - 1. Runs in the same O(log m) time and O(s) space without relying on standard-library bisect helpers.
  • Single list of (timestamp, value) tuples with chr(127) sentinel: Works if you search with (query_time, chr(127)) since ASCII 127 sorts 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 via bisect.insort shifts elements in O(m) time per write. To maintain O(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, Java TreeMap, or Python's sortedcontainers.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, and end_idx = bisect_right(key_times, t_end) locates the slice boundary just past the last write <= t_end. Slicing zip(key_times[start_idx:end_idx], key_values[start_idx:end_idx]) runs in O(log m + k) time, where k is 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 days below 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

Similar questions

More Oracle interview questions

All 104 Oracle questions →