
Sponsored
Sponsored
This approach uses a HashMap where each key points to a sorted list of timestamp-value pairs. The 'set' function appends the value along with the timestamp to the list associated with the key. The 'get' function retrieves the value at a particular timestamp by performing a binary search to find the rightmost timestamp less than or equal to the requested timestamp.
Time Complexity: O(log n) for the 'get' operation and O(1) for the 'set' operation in terms of inserting, where n is the number of entries per key.
Space Complexity: O(n), where n is the number of entries in the TimeMap.
1from bisect import bisect_right
2class TimeMap:
3 def __init__(self):
4 self.store = {}
5 def set(self, key: str, value: str, timestamp: int) -> None:
6 if key not in self.store:
7 self.store[key] = []
8 self.store[key].append((timestamp, value))
9 def get(self, key: str, timestamp: int) -> str:
10 if key not in self.store:
11 return ""
12 values = self.store[key]
13 i = bisect_right(values, (timestamp, chr(127)))
14 if i == 0:
15 return ""
16 return values[i-1][1]In the Python solution, we employ the 'bisect_right' function from the 'bisect' module to perform a binary search. The key-value pairs are stored such that each key corresponds to a list of (timestamp, value) tuples. The 'set' method stores the new data point in logarithmic time complexity due to the sorted insertion. The 'get' method uses binary search to efficiently find the largest timestamp less than or equal to the given timestamp.
This approach is similar, but instead of using a helper library for the binary search, we implement it manually. This approach provides more control over the binary search process.
Time Complexity: O(log n) for the 'get' operation and O(1) for the 'set' operation, where n is the number of entries per key.
Space Complexity: O(n) total space used by the data structure, where n is total number of stored key-value pairs.
1#include <unordered_map>
2#include <vector>
3#include <string>
4#include <algorithm>
5using namespace std;
class TimeMap {
unordered_map<string, vector<pair<int, string>>> store;
public:
void set(string key, string value, int timestamp) {
store[key].emplace_back(timestamp, value);
}
string get(string key, int timestamp) {
if (store.find(key) == store.end()) return "";
auto& values = store[key];
int left = 0, right = values.size();
while (left < right) {
int mid = (left + right) / 2;
if (values[mid].first <= timestamp) left = mid + 1;
else right = mid;
}
return right > 0 ? values[right - 1].second : "";
}
};In C++, we use an unordered_map to keep track of all the keys. Every key maps to a vector of pairs, where each pair is a timestamp and its corresponding value. By manually coding the binary search, we find the accurate position to get the right timestamp in logarithmic time complexity.