InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Time Based Key-Value Store

medium Original ↗ 00:00

Problem

Design a key-value store where every write is stamped with a time, and reads ask for the value “as of” a given time. Implement a class TimeMap with:

  • set(key, value, timestamp) — store value under key at time timestamp.
  • get(key, timestamp) — return the value written to key with the largest timestamp_prev <= timestamp. If no write to key happened at or before that time, return "".

For each key, all set calls arrive with strictly increasing timestamps.

Examples

  • set("foo","bar",1); get("foo",1)"bar"; get("foo",3)"bar" At time 3 the latest write at-or-before is still the one from time 1.
  • Continuing: set("foo","bar2",4); get("foo",4)"bar2"; get("foo",5)"bar2" The write at time 4 supersedes the earlier one for queries at time ≥ 4.
  • get("missing", 10)""; and after only set("a","x",5), get("a", 4)"" Unknown key, or a query time earlier than the first write, both return the empty string.

Constraints

  • 1 <= len(key), len(value) <= 100, lowercase letters and digits.
  • 1 <= timestamp <= 10^7; timestamps for set are strictly increasing per key.
  • Up to 2 * 10^5 total calls to set and get — each get must beat a linear scan over that key’s history.

Think about it first

Hint 1 Per key you need the full history of writes, not just the latest value. What does the strictly-increasing-timestamp guarantee tell you about the order of that history?
Hint 2 Each key's history is a list already sorted by timestamp. "Largest timestamp ≤ query" is a predecessor query on a sorted list — which algorithm answers that in O(log n)?
Hint 3 Keep `dict: key -> list of (timestamp, value)` and answer `get` with `bisect_right` on the timestamps: the candidate is the entry just before the insertion point; if the insertion point is 0, no write qualifies and you return `""`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug