Map of lists + binary search
Time O(1) set, O(log n) get Space O(total sets)key → ArrayList of (time, value). get finds the rightmost time ≤ t.
set(foo, bar, 1), get(foo, 1), get(foo, 3), set(foo, bar2, 4), get(foo, 4), get(foo, 5)values[foo](list)
Step 1/5set(foo, bar, 1): append time 1 to foo's times list and bar to its values list.
import java.util.*;
class TimeMap {
private final Map<String, List<Integer>> times = new HashMap<>();
private final Map<String, List<String>> values = new HashMap<>();
public TimeMap() {}
public void set(String key, String value, int timestamp) {
times.computeIfAbsent(key, k -> new ArrayList<>()).add(timestamp);
values.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
public String get(String key, int timestamp) {
List<Integer> t = times.get(key);
if (t == null) return "";
int lo = 0, hi = t.size(); // first index with time > timestamp
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (t.get(mid) <= timestamp) lo = mid + 1; else hi = mid;
}
return lo == 0 ? "" : values.get(key).get(lo - 1);
}
}Verdict: No TreeMap overhead.