Skip to content

Commit 32f0415

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 981_Time_Based_Key-Value_Store.java
1 parent f3a1f4c commit 32f0415

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class TimeMap {
2+
private Map<String, List<Node>> hm;
3+
4+
public TimeMap() {
5+
hm = new HashMap<>();
6+
}
7+
8+
public void set(String key, String value, int timestamp) {
9+
hm.putIfAbsent(key, new ArrayList<>());
10+
hm.get(key).add(new Node(timestamp, value));
11+
}
12+
13+
public String get(String key, int timestamp) {
14+
if (!hm.containsKey(key)) {
15+
return "";
16+
}
17+
18+
List<Node> nodes = hm.get(key);
19+
int low = 0, high = nodes.size() - 1;
20+
21+
while (low < high) {
22+
int mid = low + (high - low) / 2;
23+
24+
if (nodes.get(mid).timestamp == timestamp) {
25+
return nodes.get(mid).value;
26+
}
27+
28+
if (nodes.get(mid).timestamp < timestamp) {
29+
if (nodes.get(mid + 1).timestamp > timestamp) {
30+
return nodes.get(mid).value;
31+
}
32+
33+
low = mid + 1;
34+
} else {
35+
high = mid - 1;
36+
}
37+
}
38+
39+
return nodes.get(low).timestamp <= timestamp ? nodes.get(low).value : "";
40+
}
41+
42+
private class Node {
43+
private int timestamp;
44+
private String value;
45+
46+
public Node(int t, String v) {
47+
timestamp = t;
48+
value = v;
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)