Overview
Design a time-based key-value store that supports:
set(key, value, timestamp)— store the key-value pair at the given timestampget(key, timestamp)— return the value with the largest timestamp ≤ given timestamp, or""if none exists
Timestamps in set are strictly increasing.
Constraints
1 <= key.length, value.length <= 100- Timestamps are positive integers.
settimestamps are strictly increasing for the same key.
Examples
const store = new TimeMap();
store.set("foo", "bar", 1);
store.get("foo", 1); // => "bar"
store.get("foo", 3); // => "bar"
store.set("foo", "bar2", 4);
store.get("foo", 4); // => "bar2"
store.get("foo", 5); // => "bar2"Solution
Reveal solution
class TimeMap {
constructor() { this.map = {}; }
set(key, value, timestamp) {
if (!this.map[key]) this.map[key] = [];
this.map[key].push([timestamp, value]);
}
get(key, timestamp) {
const entries = this.map[key] || [];
let lo = 0, hi = entries.length - 1, result = "";
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (entries[mid][0] <= timestamp) { result = entries[mid][1]; lo = mid + 1; }
else hi = mid - 1;
}
return result;
}
}Resources
time-based-key-value-store.js
Time Based Key-Value Store
mediumcodingAlgorithmsBinary Search
Overview
Design a time-based key-value store that supports:
set(key, value, timestamp)— store the key-value pair at the given timestampget(key, timestamp)— return the value with the largest timestamp ≤ given timestamp, or""if none exists
Timestamps in set are strictly increasing.
Constraints
1 <= key.length, value.length <= 100- Timestamps are positive integers.
settimestamps are strictly increasing for the same key.
Examples
const store = new TimeMap();
store.set("foo", "bar", 1);
store.get("foo", 1); // => "bar"
store.get("foo", 3); // => "bar"
store.set("foo", "bar2", 4);
store.get("foo", 4); // => "bar2"
store.get("foo", 5); // => "bar2"Solution
Reveal solution
class TimeMap {
constructor() { this.map = {}; }
set(key, value, timestamp) {
if (!this.map[key]) this.map[key] = [];
this.map[key].push([timestamp, value]);
}
get(key, timestamp) {
const entries = this.map[key] || [];
let lo = 0, hi = entries.length - 1, result = "";
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (entries[mid][0] <= timestamp) { result = entries[mid][1]; lo = mid + 1; }
else hi = mid - 1;
}
return result;
}
}Resources
NameTopicDifficulty
103 of 103 problems