MediumNo. 0981
Time Based Key-Value Store — LeetCode 981 Python Solution
- Pattern
- Binary Search
- Topics
- Design, Hash Table, String, Binary Search
- On study lists
- NeetCode 150 and Grind 75
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure.
Example
- Input
- ["TimeMap", "set", "get", "get", "set", "get", "get"]
- Output
- [null, null, "bar", "bar", null, "bar2", "bar2"]
- Explanation
- TimeMap timeMap = new TimeMap();
Python solution
class TimeMap:
def __init__(self):
self.ktv = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.ktv[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
if key not in self.ktv:
return ''
tv = self.ktv[key]
i = bisect_right(tv, (timestamp, chr(127)))
return tv[i - 1][1] if i else ''
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)Complexity
- Time
- O(1)
- Space · auxiliary
- O(n)where n is the number of set operations
Pattern: Binary Search
Halve the search space each step — over an array, or over the answer itself. LeetCode 981. Time Based Key-Value Store is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.
The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1348 | Tweet Counts Per Frequency | Medium |
| 0208 | Implement Trie (Prefix Tree) | Medium |
| 0352 | Data Stream as Disjoint Intervals | Hard |
| 0535 | Encode and Decode TinyURL | Medium |
| 0676 | Implement Magic Dictionary | Medium |
| 0677 | Map Sum Pairs | Medium |
Frequently asked questions
- How hard is LeetCode 981. Time Based Key-Value Store?
LeetCode 981. Time Based Key-Value Store is rated Medium on LeetCode.
- What is the time complexity of LeetCode 981. Time Based Key-Value Store?
The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 981. Time Based Key-Value Store?
The Python solution on this page uses O(n), where n is the number of \textit{set} operations auxiliary space.
- What topics does LeetCode 981. Time Based Key-Value Store cover?
LeetCode 981. Time Based Key-Value Store is tagged Design, Hash Table, String and Binary Search on LeetCode.