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 recording value for key at integer time timestamp while retaining all previously stored versions of key.
  • ("get", key, timestamp) — Query the value associated with key as of integer time timestamp.

Process operations strictly from left to right and enforce these lookup semantics:

  1. Sequential visibility: A "get" operation may only inspect "set" operations for the same key that appear earlier in operations. Writes appearing later in operations are invisible to earlier reads regardless of their timestamps.
  2. Timestamp selection: Among visible writes for key, return the value belonging to the write with the largest timestamp less than or equal to the "get" timestamp.
  3. Missing or future-only history: If key has no prior writes, or if every prior write to key occurred strictly after the "get" timestamp, return "".
  4. Output format: Collect and return one string per "get" operation in the order those queries occur. If operations contains 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 key and value consists of 1 to 100 lowercase ASCII letters (a–z) and digits (0–9).
  • 1 <= timestamp <= 10^7 across all "set" and "get" commands.
  • Across all "set" operations in operations (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

  1. 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 of key stamped at timestamp.
    • ("get", key, query_time) looks up the version key held as of query_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:

    1. Timestamp rule (<= query_time): Among visible writes to key, pick the one with the largest timestamp <= query_time (or "" if none qualifies).
    2. List-order rule (earlier in operations): Only "set" commands appearing before this "get" in operations are visible, even when query_time lies far in the future.
  2. 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,000 operations, imagine 100,000 "set" writes to one popular key "hot", followed by 100,000 "get" queries asking about early timestamps:

    • Scanning forward inspects up to 100,000 versions per read.
    • Scanning backward from newest to oldest still walks nearly all 100,000 versions whenever query_time sits near the beginning of history.

    Either linear scan performs roughly 100,000 * 100,000 = 10^10 comparisons and times out. Reads need O(log V) time over V versions rather than O(V).

  3. 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:

    1. Replaying operations sequentially guarantees that whenever a "get" executes, the store contains only "set" commands that appeared earlier in operations.
    2. 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_time form a contiguous prefix on the left, while timestamps > query_time sit on the right. Python's bisect_right(key_times, query_time) runs binary search to find that split index valid_count in O(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_right over bisect_left?

    • bisect_left([3, 10, 18, 24], 10) returns 1 (the count of timestamps strictly < 10), skipping the version written at exact time 10!
    • bisect_right([3, 10, 18, 24], 10) returns 2 (the count of timestamps <= 10). Whenever valid_count == 0, no timestamp satisfies <= query_time so we return ""; otherwise valid_count - 1 points to the latest qualifying version.
  4. Build the store: O(1) versioned writes

    We encapsulate the state inside VersionedStore using two parallel dictionaries keyed by key:

    • 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] lets bisect_right compare 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)
    
  5. Add O(log V) point-in-time reads

    Inside get(self, key, query_time):

    1. If key has no recorded writes (key not in self.times), return "".
    2. Compute valid_count = bisect_right(self.times[key], query_time).
    3. If valid_count == 0, every recorded write happened strictly after query_time, so return "".
    4. 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]
    
  6. 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 operations is replayed in a single pass, an earlier "get" never observes a later "set".

  7. Complete solution

    Here is the complete VersionedStore class and run_versioned_store driver:

    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 an O(1) average-time dictionary lookup and two amortized O(1) list appends (meaning O(1) per append on average across dynamic array resizes). Each "get" performs an O(1) dictionary lookup and one bisect_right binary search over at most S timestamps for that key in O(log S) time.
  • Space: O(S + G) to store the S historical (timestamp, value) entries across all keys plus the G output strings in results.

Edge cases

  • Key never written: key not in self.times immediately returns "".
  • Query timestamp earlier than the key's first write: bisect_right returns 0, cleanly yielding "".
  • Query timestamp equal to a write timestamp: Included by <=, which is why we use bisect_right rather than bisect_left.
  • Future query timestamp before a later write in operations: Replaying operations sequentially 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_left instead of bisect_right: bisect_left([3, 10], 3) returns 0, missing a version written at exact timestamp 3.
  • Loading all "set" commands in pass 1 and answering "get" commands in pass 2: Breaks sequential visibility because earlier reads would see future writes in operations.
  • 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() on times[key] during writes or reads: Wastes O(V log V) work per step because strictly increasing "set" timestamps keep times[key] sorted on append.
  • Returning None instead 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 update ans = mid whenever key_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; parallel times and values lists 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 via bisect.insort shifts elements in O(V) time per write. To keep both writes and historical reads in O(log V) time, store each key's versions in a balanced binary search tree or a skip list (a randomized multi-level linked list supporting O(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 than T_gc can be discarded except the single newest version at or before T_gc, which is still required to answer queries at T_gc. Any query with query_time < T_gc should raise a retention-expired error rather than returning "", and compacting expired prefixes from sorted version lists reclaims space in amortized O(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 time 2 returns "n1" and a subsequent set("host", "n2", 8) changes what get("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 above T, or by serving lock-free historical reads only at T <= closed_timestamp once the cluster guarantees no future write can commit at or below T.

Follow-up questions

Similar questions

More Cockroach Labs interview questions

All 2 Cockroach Labs questions →