SDE & MLE Prep

981. Time Based Key-Value Store

Problem

Design TimeMap, a key-value store that keeps every version: set(key, value, timestamp) stores a value at a time, and get(key, timestamp) returns the value set at the largest timestamp ≤ timestamp, or "" if there is none. Timestamps of set calls are strictly increasing.

Example: set("foo","bar",1); get("foo",3) → "bar"; set("foo","bar2",4); get("foo",4) → "bar2"

Timestamps per key arrive increasing → append to a list. get = binary search for the last timestamp ≤ t.

Complexity: O(1) set, O(log n) get.

class TimeMap:
    def __init__(self):
        self.data = defaultdict(list)  # key -> [(ts, value)]

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.data[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        arr = self.data.get(key, [])
        i = bisect.bisect_right(arr, (timestamp, chr(0x10FFFF)))  # first ts > timestamp
        return arr[i - 1][1] if i else ""