Time Based Key-Value Store
Medium
Topics
Design TimeMap with set(key, value, timestamp) and get(key, timestamp). get returns the value set for key with the largest timestamp <= timestamp, or an empty string if none.
Example 1
A
get wants the newest value at or before a timestamp, not an exact match.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["TimeMap","set","get","get","set","get","get"], values = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]] Output: [null,null,bar,bar,null,bar2,bar2]
Constraints
- 1 <= key.length, value.length <= 100
- set timestamps are strictly increasing per problem.
- At most 2*10^5 calls.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Because set timestamps are increasing, each key stores an ascending list of (timestamp, value). A get is then a binary search for the rightmost timestamp not exceeding the query.
Approach
- Keep a map from key to a list of (timestamp, value) pairs appended in order.
- For get, binary search that list for the largest timestamp <= query.
- Return the paired value, or "" if none qualifies.
Dry Run
TimeMap()
set foo bar 1 -> null store[foo] = [(1, bar)]
get foo 1 -> "bar" exact match on the timestamp counts
get foo 3 -> "bar" nothing newer than 3, so the 1 still answers
set foo bar2 4 -> null store[foo] = [(1, bar), (4, bar2)]
get foo 4 -> "bar2"
get foo 5 -> "bar2"
get foo 0 -> "" nothing at or before 0
answer null|null|bar|bar|null|bar2|bar2
The binary search finds the first entry STRICTLY AFTER the timestamp, so the
answer sits one position back at arr[lo - 1], and `if lo else ""` covers the case
where even the oldest entry is too new. Return arr[lo] instead and every get
comes back empty or out of range -- the whole sequence degenerates to blanks.
The comparison is `<=`, not `<`. An exact timestamp match is a valid answer, and
`<` steps over it: `get foo 1` then returns "" and `get foo 4` returns "bar",
each reading the value from before the set it should have seen.
Appends arrive in increasing timestamp order, which is the only reason a binary
search is legal with no sorting anywhere. If timestamps could arrive out of order
this would need an insort, and the amortised O(1) set would become O(n).Complexity
- Time — O(log n) get: binary search per get; O(1) amortized set.
- Space — O(n): all set entries.
Common Pitfalls
- The binary search finds the first entry after the timestamp, so the answer is
arr[lo - 1]. Returningarr[lo]reads one past the newest match and raisesIndexErrorat the end of the list. - The comparison is
<=, not<. An exact timestamp match is a valid answer, and<steps over it --getat the moment of asetreturns the previous value or nothing. - Appends are already in increasing timestamp order, which is the only reason a binary search is legal without sorting. If timestamps could arrive out of order this would need an insort.
Full Solution — all languages
class TimeMap:
def __init__(self):
self.store = {}
def set(self, key, value, timestamp):
self.store.setdefault(key, []).append((timestamp, value))
def get(self, key, timestamp):
arr = self.store.get(key, [])
lo, hi = 0, len(arr)
while lo < hi: # binary search: timestamps are increasing
mid = (lo + hi) // 2
if arr[mid][0] <= timestamp:
lo = mid + 1
else:
hi = mid
return arr[lo - 1][1] if lo else ""import java.util.*;
class TimeMap {
Map<String, List<Object[]>> store = new HashMap<>();
public TimeMap() {
}
public void set(String key, String value, int timestamp) {
store.computeIfAbsent(key, z -> new ArrayList<>()).add(new Object[]{timestamp, value});
}
public String get(String key, int timestamp) {
List<Object[]> arr = store.getOrDefault(key, new ArrayList<>());
int lo = 0, hi = arr.size();
// binary search: timestamps are increasing
while (lo < hi) {
int mid = (lo + hi) / 2;
if ((int) arr.get(mid)[0] <= timestamp) lo = mid + 1;
else hi = mid;
}
return lo > 0 ? (String) arr.get(lo - 1)[1] : "";
}
}#include <bits/stdc++.h>
using namespace std;
class TimeMap {
unordered_map<string, vector<pair<int, string>>> store;
public: TimeMap() {
}
void set(string key, string value, int timestamp) {
store[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
auto& arr = store[key];
int lo = 0, hi = (int)arr.size();
// binary search: timestamps are increasing
while (lo < hi) {
int mid = (lo + hi) / 2;
if (arr[mid].first <= timestamp) lo = mid + 1;
else hi = mid;
}
return lo ? arr[lo - 1].second : "";
}
};class TimeMap {
constructor() {
this.store = {};
}
set(key, value, timestamp) {
(this.store[key] = this.store[key] || []).push([timestamp, value]);
}
get(key, timestamp) {
const arr = this.store[key] || [];
let lo = 0, hi = arr.length;
// binary search: timestamps are increasing
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid][0] <= timestamp) lo = mid + 1;
else hi = mid;
}
return lo ? arr[lo - 1][1] : "";
}
}