From a148ec2b747d556d8825681c06d5b9d4d60cbad8 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Fri, 24 Nov 2023 08:44:18 -0700 Subject: [PATCH] day 42: 981-time-based-key-value-store --- 981-time-based-key-value-store/driver.cpp | 13 ++++++ 981-time-based-key-value-store/soln.cpp | 51 +++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 981-time-based-key-value-store/driver.cpp create mode 100644 981-time-based-key-value-store/soln.cpp diff --git a/981-time-based-key-value-store/driver.cpp b/981-time-based-key-value-store/driver.cpp new file mode 100644 index 0000000..aa2413f --- /dev/null +++ b/981-time-based-key-value-store/driver.cpp @@ -0,0 +1,13 @@ +#include "soln.cpp" + +int main() +{ + TimeMap timeMap; + timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1. + cout << timeMap.get("foo", 1) << endl; // return "bar" + cout << timeMap.get("foo", 3) << endl; // 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. + cout << timeMap.get("foo", 4) << endl; // return "bar2" + cout << timeMap.get("foo", 5) << endl; // return "bar2" + return 0; +} \ No newline at end of file diff --git a/981-time-based-key-value-store/soln.cpp b/981-time-based-key-value-store/soln.cpp new file mode 100644 index 0000000..8c686e8 --- /dev/null +++ b/981-time-based-key-value-store/soln.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; +class TimeMap +{ +public: + unordered_map>> timemap; + TimeMap() + { + } + + void set(string key, string value, int timestamp) + { + timemap[key].push_back({timestamp, value}); + } + + string get(string key, int timestamp) + { + if (timemap.find(key) == timemap.end()) + { + return ""; + } + else if (timemap[key].size() == 1) + { + return timemap[key][0].first <= timestamp ? timemap[key][0].second : ""; + } + // binary search + int low = 0, high = timemap[key].size(), mid; + while (low < high) + { + mid = low + (high - low) / 2; + if (timemap[key][mid].first <= timestamp) + { + low = mid + 1; + } + else + { + high = mid; + } + } + // Now, low points to the element that succeeds the given timestamp + // so we want the one before it + return low > 0 && low <= timemap[key].size() ? timemap[key][low - 1].second : ""; + } +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap* obj = new TimeMap(); + * obj->set(key,value,timestamp); + * string param_2 = obj->get(key,timestamp); + */ \ No newline at end of file