Time Based Key-Value Store Problem
Description
LeetCode Problem 981.
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.
- void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.
- String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".
Example 1:
Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]
Explanation
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1); // return "bar"
timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4); // return "bar2"
timeMap.get("foo", 5); // return "bar2"
Constraints:
- 1 <= key.length, value.length <= 100
- key and value consist of lowercase English letters and digits.
- 1 <= timestamp <= 10^7
- All the timestamps timestamp of set are strictly increasing.
- At most 2 * 10^5 calls will be made to set and get.
Solution
Approach: Hash Map of Sorted Lists with Binary Search
The statement guarantees that the timestamps of set calls strictly increase. So if each key keeps its own list of (timestamp, value) entries and set simply appends, every list is already sorted by timestamp. No sorting or balanced tree is needed.
set(key, value, timestamp): appendtimestampandvalueto the key's lists. O(1).get(key, timestamp): binary search the key's timestamps for the number of entries with timestamp<= timestamp(an upper bound). Call itcount.- If the key does not exist or
count == 0, every stored entry is later thantimestamp, so return"". - Otherwise the answer is the value at index
count - 1, the latest entry not aftertimestamp.
- If the key does not exist or
Example: after set("foo", "bar", 1) and set("foo", "bar2", 4), the timestamps for "foo" are [1, 4]. For get("foo", 3), one entry is <= 3, so the answer is the value at index 0, "bar". For get("foo", 5), count = 2, so the answer is "bar2".
The search must find the last timestamp <= the query, not an exact match: most queries fall between stored timestamps. Searching for the first timestamp greater than the query and stepping back one handles both cases, including an exact match, with no special code.
Complexity: O(1) per set and O(log m) per get, where m is the number of entries stored for that key. O(n) space for n calls to set.
import bisect
import collections
class TimeMap:
def __init__(self):
# For each key, its timestamps and values in the order they were set.
# Timestamps of set calls strictly increase, so each list is already sorted.
self.times = collections.defaultdict(list)
self.values = collections.defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.times[key].append(timestamp)
self.values[key].append(value)
def get(self, key: str, timestamp: int) -> str:
times = self.times.get(key, [])
count = bisect.bisect_right(times, timestamp) # how many sets happened at or before timestamp
if count == 0:
return ""
return self.values[key][count - 1] # the latest of them
Now write it from memory
Close the write-up and solve it yourself against the tests.