Problem
Design a time-based key-value store. set stores a string value for a key at a timestamp, and get returns the value with the largest timestamp less than or equal to the queried time, or an empty string if there is none. Timestamps on set for the same key are strictly increasing.
Original: LeetCode 981: Time Based Key-Value Store.
Examples
Example 1
`TimeMap: set("foo", "bar", 1), get("foo", 1), get("foo", 3), set("foo", "bar2", 4), get("foo", 4), get("foo", 5)``[null, "bar", "bar", null, "bar2", "bar2"]`Constraints
1 <= key.length, value.length <= 100keyandvalueconsist of lowercase English letters and digits.1 <= timestamp <= 10^7- All the timestamps
timestampofsetare strictly increasing. - At most
2 * 10^5calls will be made tosetandget.
Hints
Hint 1
You do not have to handle a set that goes backwards in time for a given key. get may ask for a time that was never written, and should then use the previous write.
Hint 2
This is a time-indexed lookup: a map of keys to a sorted list, then a binary search (upper bound).
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Scan the list from the end until the timestamp is small enough, which is linear in the number of writes for that key.
Optimal. Because timestamps are increasing, a binary search is enough. In Java, a TreeMap per key also works.
Alternative. A global tree of timestamps is unnecessary, because queries are always per key.
Complexity
- Time
- O(1)
set is O(1). get is O(log n) in the number of writes for that key. Space is O(n).
- Space
- O(n)
Code
from bisect import bisect_right
from collections import defaultdict
class TimeMap:
def __init__(self) -> None:
self.map: dict[str, list[tuple[int, str]]] = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.map[key].append((timestamp, value))
def get(self, key: str, timestamp: int) -> str:
list_ = self.map.get(key)
if not list_:
return ""
i = bisect_right(list_, (timestamp, chr(127))) - 1
return list_[i][1] if i >= 0 else ""
if __name__ == "__main__":
kv = TimeMap()
kv.set("foo", "bar", 1)
assert kv.get("foo", 1) == "bar"
assert kv.get("foo", 3) == "bar"
kv.set("foo", "bar2", 4)
assert kv.get("foo", 4) == "bar2"
assert kv.get("foo", 5) == "bar2"
print("ok")import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TimeBasedKeyValueStore {
private final Map<String, List<Stamp>> map = new HashMap<>();
void set(String key, String value, int timestamp) {
map.computeIfAbsent(key, k -> new ArrayList<>()).add(new Stamp(timestamp, value));
}
String get(String key, int timestamp) {
var list = map.get(key);
if (list == null) return "";
int lo = 0, hi = list.size() - 1, best = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (list.get(mid).time <= timestamp) {
best = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return best == -1 ? "" : list.get(best).value;
}
static class Stamp {
int time;
String value;
Stamp(int time, String value) { this.time = time; this.value = value; }
}
public static void main(String[] args) {
var kv = new TimeBasedKeyValueStore();
kv.set("foo", "bar", 1);
if (!kv.get("foo", 1).equals("bar")) throw new AssertionError();
if (!kv.get("foo", 3).equals("bar")) throw new AssertionError();
kv.set("foo", "bar2", 4);
if (!kv.get("foo", 4).equals("bar2")) throw new AssertionError();
if (!kv.get("foo", 5).equals("bar2")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: set foo/bar at time 1, get at 1 and 3 both return "bar"; set foo/bar2 at time 4, then get at 4 and 5 return "bar2".
- A get before the first write returns "".
Follow-ups
- If set is allowed to arrive out of order, each key needs a tree map instead of an append-only list.
Interview script
"Because timestamps for a key are strictly increasing, I can append on set and binary-search on get for the rightmost time that is not after the query. If nothing is eligible, I return an empty string."
Source: LeetCode 981: Time Based Key-Value Store
Tries and prefix search
Sources (1)
- LeetCode 981: Time Based Key-Value Storeleetcode.com