Time Based Key-Value Store
LeetCode 981 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Per-key sorted list + binary search for floor(timestamp).
నేను Time Based Key-Value Store (LeetCode 981) ను ఇలా పరిష్కరించాను — Design ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, 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).
నేను ఎలా పరిష్కరించాను
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 — తరచూ అడిగే ప్రశ్నలు
Time Based Key-Value Store వెనుక ఉన్న 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.
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).
Time Based Key-Value Store యొక్క time, space complexity ఎంత?
Time: O(1) set, O(log n) get. Space: O(n). (Accepted approach: Hash map + binary search.)
Time Based Key-Value Store లో సాధారణ పొరపాట్లు ఏమిటి?
Remember the candidate when going right — that's the floor.