Time Based Key-Value Store
With dictionary:
class TimeMap(defaultdict):
def __init__(self):
super().__init__(dict)
def set(self, key: str, value: str, timestamp: int) -> None:
self[key][timestamp] = value
def get(self, key: str, timestamp: int) -> str:
max_time = 0
res = ""
for time, val in super().get(key, {}).items():
if max_time < time <= timestamp:
max_time = time
res = val
return resWith binary search
class TimeMap(defaultdict):
def __init__(self):
super().__init__(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
index = bisect_right(super().get(key, []), timestamp, key=lambda x: x[0])
return self[key][index - 1][1] if index else ""Notice the usage of bisect_right.