Time-Based Key-Value Store

set/get keyed by timestamp — per-key sorted timestamps with binary search for the largest timestamp not exceeding the query.

Medium
Time O(1) set Space O(n)
LeetCode
4 min read
design hash-map binary-search

Problem#

Design set(key, value, timestamp) and get(key, timestamp). get returns the value associated with the largest timestamp_prev <= timestamp for that key, or an empty string if none.

Examples#

  • set("foo","bar",1); get("foo",1)"bar"
  • get("foo",3)"bar" (no later set)
  • set("foo","bar2",4); get("foo",4)"bar2"

Constraints#

  • All timestamps for the same key are strictly increasing.
  • Up to 2 * 10^5 operations.

Approach#

Per key, append (timestamp, value) to a vector (already strictly increasing). On get, binary-search the vector for the rightmost timestamp <= query.

Solution#

Time-Based Key-Value Store
class TimeMap {
unordered_map<string, vector<pair<int, string>>> mp;
public:
void set(string key, string value, int timestamp) {
mp[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
auto it = mp.find(key);
if (it == mp.end()) return "";
auto& v = it->second;
int lo = 0, hi = (int)v.size() - 1, ans = -1;
while (lo <= hi) {
int m = (lo + hi) / 2;
if (v[m].first <= timestamp) { ans = m; lo = m + 1; }
else hi = m - 1;
}
return ans == -1 ? "" : v[ans].second;
}
};

Editorial#

Because timestamps per key are monotonically increasing on set, the vector is sorted “for free” — no extra sort. Binary search finds the predecessor in O(log n).

Complexity#

  • Time: O(1) set, O(log n) get.
  • Space: O(total writes).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.