Time Based Key-Value Store

MediumBinary searchLeetCode 981 ↗World 9-14
0:00 / 0:00

Store values per key with timestamps, then fetch the latest value at or before a time. Times arrive sorted, so binary search them.

▼

The problem

Design a time-based key-value store: set(key, value, timestamp) stores a value for a key at a time; get(key, timestamp) returns the value set most recently at or before that time, or "" if there is none. The timestamps of set calls are strictly increasing.

Example: set("foo", "bar", 1); get("foo", 1) → "bar"; get("foo", 3) → "bar"; set("foo", "bar2", 4); get("foo", 4) and get("foo", 5) → "bar2"; get("foo", 0) → "" (nothing set yet).

TRY IT ON LEETCODE ▶

The solution

class TimeMap:
    def __init__(self):
        self.store = {}  # key -> [(time, value)]
    def set(self, key, value, time):
        self.store.setdefault(key, []).append((time, value))
    def get(self, key, time):
        items = self.store.get(key, [])
        lo, hi, ans = 0, len(items) - 1, ""
        while lo <= hi:
            mid = (lo + hi) // 2
            if items[mid][0] <= time:
                ans, lo = items[mid][1], mid + 1
            else:
                hi = mid - 1
        return ans

Transcript

Time Based Key-Value Store. One key can hold many values, each set at its own timestamp. Get, given a key and a time, returns the value set most recently at or before that time, or an empty string if there isn't one.

Set foo to bar at time one. Get foo at one: bar. At three, nothing new was set, so it's still bar. Now set foo to bar two at time four. Get at four or five: bar two. And get at time zero returns empty: nothing was set yet.

The simple way keeps every pair for a key, and scans the whole list on each get, looking for the newest time that isn't too late. With n entries, every get costs order n.

But set's timestamps always increase. So all the lists are already sorted by time, just from appending. Get wants the last entry whose time is at most the target, and in a sorted list, binary search finds it.

In code, a dictionary maps each key to a list of time and value pairs. Set appends. Get keeps a low and a high bound, and checks the middle. If its time fits, remember its value, and look right for something newer. If it's too new, look left. When the bounds cross, return the last value that fit, or empty if none did.

Let's try it. Sky holds seven snapshots, at times one, three, five, eight, eleven, fourteen and eighteen. Get sky at twelve. The middle is eight: it fits, so remember snow, and go right. The next middle is fourteen: too new, go left. Eleven fits: remember fog. Now the bounds cross, so the answer is fog, in three checks. Get sky at zero, and every middle is too new. Nothing fit, so the answer is empty.

Set takes constant time: it just appends. Get takes log n, so a million snapshots need only about twenty checks. Space is one entry per set.

Append in order, search by time. That's Time Based Key-Value Store.