Time Based Key-Value Store — LeetCode 981 Python Solution
- Problem
- #981
- Pattern
- Binary Search
- 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
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(n), where n is the number of \textit{set} operations auxiliary |
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
On study lists
This problem is on NeetCode 150 and Grind 75.
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.