Time Based Key-Value Store — HashMap + Binary Search
Advertisement
Problem 199 · Time Based Key-Value Store
Difficulty: Medium · Pattern: HashMap + Binary Search
Design a store where each key maps to a list of (timestamp, value) pairs. get(key, timestamp) returns the value with the largest timestamp ≤ given timestamp.
Solutions
# Python
from collections import defaultdict
import bisect
class TimeMap:
def __init__(self): self.store = defaultdict(list)
def set(self, key, value, timestamp):
self.store[key].append((timestamp, value))
def get(self, key, timestamp):
lst = self.store[key]
i = bisect.bisect_right(lst, (timestamp, chr(127))) - 1
return lst[i][1] if i >= 0 else ""
// Java
class TimeMap {
Map<String, List<int[]>> map = new HashMap<>();
Map<String, List<String>> vals = new HashMap<>();
public void set(String key, String value, int timestamp) {
map.computeIfAbsent(key, k -> new ArrayList<>()).add(new int[]{timestamp});
vals.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
public String get(String key, int timestamp) {
if (!map.containsKey(key)) return "";
List<int[]> times = map.get(key);
int lo=0, hi=times.size()-1, idx=-1;
while (lo<=hi) {
int mid=(lo+hi)/2;
if (times.get(mid)[0]<=timestamp) { idx=mid; lo=mid+1; }
else hi=mid-1;
}
return idx==-1 ? "" : vals.get(key).get(idx);
}
}
// C++
class TimeMap {
unordered_map<string, vector<pair<int,string>>> store;
public:
void set(string key, string value, int timestamp) {
store[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
if (!store.count(key)) return "";
auto& v = store[key];
auto it = upper_bound(v.begin(), v.end(), make_pair(timestamp, string(200,'z')));
return it == v.begin() ? "" : prev(it)->second;
}
};
Complexity
- Time: O(1) set, O(log n) get
- Space: O(n)
Advertisement