</>

981. Time Based Key-Value Store

Medium NeetCode 150
Binary Search Time O(log n) per get, O(1) per set Space O(n)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Binary Search
Time
O(log n) per get, O(1) per set
Space
O(n)

Standard Solution (C++)

SummaryBuild a store that records values for keys at specific timestamps and can fetch, for a query timestamp, the value set at the largest timestamp not exceeding it.

Approach

Keep, per key, a list of (timestamp, value) pairs appended in increasing timestamp order.

  • Because set calls arrive with non-decreasing timestamps, each key's list stays sorted.
  • For get, binary search the list for the rightmost entry whose timestamp is at most the query.
  • Return that value, or an empty string if none qualifies.
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 it = store.find(key);
        if (it == store.end()) return "";
        auto& vec = it->second;
        int lo = 0, hi = vec.size() - 1;
        string result = "";
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (vec[mid].first <= timestamp) {
                result = vec[mid].second;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return result;
    }
};
Time O(log n) per get, O(1) per set Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern