Time Based Key-Value Store
Design a key-value store that remembers every value a key has had over time. Implement the TimeMap class:
TimeMap()creates an empty store.set(key, value, timestamp)records thatkeyhadvalueat timetimestamp.get(key, timestamp)returns the valuekeyhad at timetimestamp: the value from the latestsetwhose timestamp is at mosttimestamp. If there's no suchset, return an empty string.
Timestamps passed to set are strictly increasing across all calls. The tests run a sequence of operations on one store and check the value returned by every get, in order. Timestamps appear as strings in the test input and are converted to integers before each call.
Example 1
Input: ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["color", "red", "1"], ["color", "1"], ["color", "3"], ["color", "blue", "4"], ["color", "4"], ["color", "5"]] Output: ["red", "red", "blue", "blue"]
At time 3, the latest value set for color is still "red". From time 4 on, it's "blue".
Example 2
Input: ["TimeMap", "get", "set", "get", "get"] [[], ["a", "1"], ["a", "x", "5"], ["a", "4"], ["b", "5"]] Output: ["", "", ""]
Nothing was set for a at or before time 1 or time 4, and b was never set.
Constraints
1 <= key.length, value.length <= 100keyandvaluecontain lowercase English letters and digits.1 <= timestamp <= 10^7- Timestamps passed to
setare strictly increasing. - At most
2 * 10^5calls are made tosetandget.
Approach
Store a list of (timestamp, value) pairs for each key in a hash map. Because timestamps given to set only increase, appending to the end keeps each list sorted for free, so set is O(1).
For get, scanning a key's list backward until you reach an early enough timestamp works, but it's O(n) per call when a key has a long history. Since the list is sorted, binary search for the boundary instead: the first entry with a timestamp greater than the one asked for. The entry just before that boundary is the latest one at or before the requested time. If the boundary is at index 0, every entry is too late, so return an empty string.
Steps
- Keep a map from each key to a list of
(timestamp, value)pairs. - In
set, append the pair to the key's list. - In
get, binary search the key's list for the first timestamp greater thantimestamp. - If that index is
0, or the key has no list, return"". Otherwise return the value just before it.
from collections import defaultdict
class TimeMap:
def __init__(self):
# key -> list of (timestamp, value), in increasing timestamp order
# because set is always called with increasing timestamps
self.history = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.history[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
entries = self.history.get(key, [])
# Binary search for the last entry with a timestamp <= the one asked for.
lo, hi = 0, len(entries)
while lo < hi:
mid = (lo + hi) // 2
if entries[mid][0] <= timestamp:
lo = mid + 1
else:
hi = mid
return entries[lo - 1][1] if lo > 0 else ""Complexity
- Time:
O(1)forsetandO(log n)forget, wherenis the number of values stored for that key. - Space:
O(total calls to set)for the histories.
Common mistakes
- Searching for an exact timestamp match.
getusually asks for a time between twosetcalls. - Returning the first entry after the requested time instead of the last entry at or before it.
- Overwriting a key's value on each
set, which loses the history thatgetneeds.