progress

~/problems / Stateful stores / Time-travel key-value store

Time-Based Key-Value Store

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~15 min Citadel

Implement TimeMap, a key-value store that remembers every version of each key:

  • set(key, value, timestamp): store value for key as of timestamp.
  • get(key, timestamp): return the value from the set on key with the largest timestamp <= timestamp, or "" if there is none (unknown key, or every version is newer).

For all set calls, timestamps are strictly increasing across the whole store, so each key's history is appended already sorted.

tm = TimeMap()
tm.set("door", "open", 5)
tm.set("door", "shut", 9)
tm.get("door", 4)    # ""      (nothing that early)
tm.get("door", 5)    # "open"
tm.get("door", 8)    # "open"
tm.get("door", 100)  # "shut"
tm.get("lamp", 7)    # ""

Constraints: timestamps up to 10**7; up to ~10^5 calls, possibly all on one key.

⭐ Bonus: scanning a key's whole history per get still passes; a speed test with a long history earns a star at O(log n) per get.

Show hint

Because timestamps only increase, appending to per-key lists keeps each key's history sorted, so get can binary-search it (bisect_right).

Topic: Time-travel key-value store. Per-key sorted history + binary search on timestamp.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc