-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0981-time-based-key-value-store.py
More file actions
47 lines (42 loc) · 1.18 KB
/
0981-time-based-key-value-store.py
File metadata and controls
47 lines (42 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# set()
# time complexity: O(m*l)
# space complexity: O(l)
# get()
# time complexity: O(n*timestamp*l)
# space complexity: O(1)
from collections import defaultdict
class TimeMap:
def __init__(self):
self.map = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.map[key].append([timestamp, value])
def get(self, key: str, timestamp: int) -> str:
if key not in self.map:
return ""
currKeyList = self.map[key]
if timestamp < currKeyList[0][0]:
return ""
left = 0
right = len(currKeyList)
while left < right:
mid = (left + right) // 2
midTime, midVal = currKeyList[mid]
if midTime == timestamp:
return midVal
if midTime < timestamp:
left = mid + 1
else:
right = mid
return "" if right == 0 else currKeyList[right-1][1]
'''
{
'foo': [[1, 'bar'], [4, 'bar2]]
}
'''
timeMap = TimeMap()
timeMap.set("foo", "bar", 1)
print(timeMap.get("foo", 1))
print(timeMap.get("foo", 3))
timeMap.set("foo", "bar2", 4)
print(timeMap.get("foo", 4))
print(timeMap.get("foo", 5))