[LeetCode] Time Based Key-Value Store

981. Time Based Key-Value Store

Create a timebased key-value store class TimeMap, that supports two operations.

  1. set(string key, string value, int timestamp)

    • Stores the key and value, along with the given timestamp.
  2. get(string key, int timestamp)

    • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
    • If there are multiple such values, it returns the one with the largest timestamp_prev.
    • If there are no values, it returns the empty string (“”).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class TimeMap {
unordered_map<string, map<int, string>> m;
public:
/** Initialize your data structure here. */
TimeMap() {}

void set(string key, string value, int timestamp) {
m[key][timestamp] = value;
}

string get(string key, int timestamp) {
auto res = m[key].upper_bound(timestamp);
return res == m[key].begin() ? "" : prev(res)->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);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/time-based-key-value-store/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.