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.