Time Based Key-Value Store
LeetCode 981 · Medium · solution, intuition & step-by-step walkthrough
Per-key sorted list + binary search for floor(timestamp).
This is how I solved Time Based Key-Value Store (LeetCode 981), a medium problem from the Design pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
For each key, store (timestamp, value) pairs in the order they arrive — timestamps only increase, so the list is sorted. A get is then a binary search for the latest timestamp ≤ the query.
Approach
- 1
set: append [timestamp, value] to the key's list.
- 2
get: if the key is missing or the query is before the first timestamp, return ''.
- 3
Binary search; on a smaller timestamp remember its value and go right.
- 4
Return the remembered value (or the exact match).
How I solved it
Hash map + binary searchPythonO(log n) get
class TimeMap:
def __init__(self):
self.time_key_map= defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.time_key_map[key].append([timestamp,value])
def get(self, key: str, timestamp: int) -> str:
if key not in self.time_key_map:
return ""
if timestamp<self.time_key_map[key][0][0]:
return ""
low = 0
high = len(self.time_key_map[key])-1
res=""
while low<=high:
mid = (low+high)//2
mid_time_stamp_key = self.time_key_map[key][mid][0]
if mid_time_stamp_key==timestamp:
return self.time_key_map[key][mid][1]
elif mid_time_stamp_key>timestamp:
high= mid-1
else:
low = mid+1
res=self.time_key_map[key][mid][1]
return res
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)Time Based Key-Value Store — FAQ
What is the intuition behind Time Based Key-Value Store?
For each key, store (timestamp, value) pairs in the order they arrive — timestamps only increase, so the list is sorted. A get is then a binary search for the latest timestamp ≤ the query.
How do you solve Time Based Key-Value Store (LeetCode 981)?
1. set: append [timestamp, value] to the key's list. 2. get: if the key is missing or the query is before the first timestamp, return ''. 3. Binary search; on a smaller timestamp remember its value and go right. 4. Return the remembered value (or the exact match).
What is the time and space complexity of Time Based Key-Value Store?
Time: O(1) set, O(log n) get. Space: O(n). (Accepted approach: Hash map + binary search.)
What are common mistakes in Time Based Key-Value Store?
Remember the candidate when going right — that's the floor.