InterviewPrepKit

Home / Coding / Binary Search

Time Based Key-Value Store

medium Original ↗
Solving tips
  • Exploit the strictly-increasing-timestamp guarantee: each key's history is already sorted, so set is a plain O(1) append with no sorting or sorted-insert needed.
  • get is a predecessor query (largest timestamp <= query): use bisect_right on the timestamps, then the candidate is index bisect_right - 1; index 0 means no valid write, return "".
  • Use bisect_right, not bisect_left, so a write at exactly the query timestamp is returned rather than skipped.
  • Store parallel times/values lists per key (or use bisect key= on Python 3.10+) so you compare plain ints; get is O(log n), space O(N).

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 "".

A crucial guarantee: 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 give you for free about 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 `""`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.