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 "".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
1 <= key.length, value.length <= 100key and value consist of lowercase English letters and digits.timestamp of set are strictly increasing.set and get.The simplest approach to solve this problem is to use a HashMap where the keys are strings and the values are lists of pairs (timestamp, value). To perform the get operation, we can iterate over the list for a particular key and find the largest timestamp that is less than or equal to the given timestamp.
HashMap<String, List<Pair<Integer, String>>> to store keys with their associated timestamp-value pairs.set operation, we'll add a pair of (timestamp, value) to the list corresponding to the key.get operation, we'll iterate through the list associated with the given key and check for the largest timestamp that is less than or equal to the given timestamp.set: O(1) amortized time complexity.get: O(n) where n is the number of timestamp-value pairs for the key.An optimized approach improves the get operation by using binary search. Given that the timestamps are stored in sorted order by insertion, we can utilize binary search to quickly locate the largest timestamp that is less than or equal to the given timestamp.
HashMap with lists of pairs for each key.set operation, the implementation remains the same.get operation, use binary search on the list of pairs for the given key instead of linear search.set: O(1) amortized time complexity.get: O(log n), where n is the number of timestamp-value pairs for the key due to binary search.