PracticeNeetCode ↗LeetCode ↗
Design a time-based key-value store that can hold multiple values for the same key at different timestamps, and retrieve the value for a key as of a given timestamp — specifically, the value recorded at the largest timestamp not exceeding the query timestamp, or an empty string if none exists.
set: append the new (timestamp, value) pair to the list stored under that key.get: if the key has never been set, return an empty string.Time: O(1) for set, O(log n) for get — Space: O(n)
class TimeMap:
def __init__(self):
self.store = {}
def set(self, key: str, value: str, timestamp: int) -> None:
self.store.setdefault(key, []).append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if key not in self.store:
return ""
entries = self.store[key]
left, right = 0, len(entries) - 1
result = ""
while left <= right:
mid = left + (right - left) // 2
if entries[mid][0] <= timestamp:
result = entries[mid][1]
left = mid + 1
else:
right = mid - 1
return resultHow the solution above works, piece by piece.
store maps each key to a list of (timestamp, value) pairs.set appends. Timestamps arrive in increasing order, so the list stays sorted with no extra work: O(1).get binary-searches that list for the last timestamp ≤ the requested one.entries[mid][0] <= timestamp, it's a valid answer: remember it and look right for a later one. Otherwise look left.result stays "". get is O(log n) per call.Running the example calls on key "foo":
get binary-searches for the last entry with timestamp ≤ the asked time. At t = 3 nothing new was set, so it still returns "bar".