981. Time Based Key-Value Store
Asked at 32Apple68Amazon49Microsoft35Google33Bloomberg28Meta20Compass100Netflix89Lyft87Citadel84Axon100Confluent93Flexport92Coinbase91Gusto83Verkada81OpenAI79Databricks78Instacart75eBay71MongoDB71VMware69LiveRamp67CrowdStrike65Snowflake63Oracle60Anduril60Uber57Rippling46Walmart Labs43Cisco37TikTok35
Problem
Design TimeMap, a key-value store that keeps every version: set(key, value, timestamp) stores a value at a time, and get(key, timestamp) returns the value set at the largest timestamp ≤ timestamp, or "" if there is none. Timestamps of set calls are strictly increasing.
Example: set("foo","bar",1); get("foo",3) → "bar"; set("foo","bar2",4); get("foo",4) → "bar2"
Timestamps per key arrive increasing → append to a list. get = binary search for the last timestamp ≤ t.
Complexity: O(1) set, O(log n) get.
class TimeMap:
def __init__(self):
self.data = defaultdict(list) # key -> [(ts, value)]
def set(self, key: str, value: str, timestamp: int) -> None:
self.data[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
arr = self.data.get(key, [])
i = bisect.bisect_right(arr, (timestamp, chr(0x10FFFF))) # first ts > timestamp
return arr[i - 1][1] if i else ""
tm = TimeMap()
tm.set("foo", "bar", 1)
assert tm.get("foo", 1) == "bar" and tm.get("foo", 3) == "bar"
tm.set("foo", "bar2", 4)
assert tm.get("foo", 4) == "bar2" and tm.get("foo", 5) == "bar2" and tm.get("foo", 0) == ""
class TimeMap {
private final Map<String, TreeMap<Integer, String>> data = new HashMap<>();
public void set(String key, String value, int timestamp) {
data.computeIfAbsent(key, k -> new TreeMap<>()).put(timestamp, value);
}
public String get(String key, int timestamp) {
TreeMap<Integer, String> t = data.get(key);
if (t == null) return "";
Map.Entry<Integer, String> e = t.floorEntry(timestamp); // largest ts <= timestamp
return e == null ? "" : e.getValue();
}
}
type entry struct {
ts int
value string
}
type TimeMap struct {
data map[string][]entry // timestamps arrive increasing
}
func Constructor() TimeMap {
return TimeMap{data: map[string][]entry{}}
}
func (this *TimeMap) Set(key string, value string, timestamp int) {
this.data[key] = append(this.data[key], entry{timestamp, value})
}
func (this *TimeMap) Get(key string, timestamp int) string {
arr := this.data[key]
i := sort.Search(len(arr), func(i int) bool { return arr[i].ts > timestamp }) // first ts > timestamp
if i == 0 {
return ""
}
return arr[i-1].value
}