#981
Time Based Key-Value Store
specialist · 885 · lc medium +31 · 49.8% accepted · 5,249 likes · top 37%
Description
Implement TimeMap, a time-stamped key-value store:
- TimeMap() initializes the structure.
- void set(String key, String value, int timestamp) saves value under key at timestamp (timestamps are strictly increasing).
- String get(String key, int timestamp) returns the value stored for key at the greatest timestamp ≤ the given one, or "" if no such entry exists.
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"]
Example 2:
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"
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16