Skip to content

Time Based Key-Value Store

MediumBinary Search
Decode it first. Clues, constraints, pattern and plan before any code.

Design a class TimeMap that stores several values for the same key at different times, and can look up a key as of a given moment.

  • set(key, value, timestamp) stores value for key at time timestamp.
  • get(key, timestamp) returns the value stored for key with the largest timestamp that is <= timestamp. If there is none, return "".
tm = TimeMap()
tm.set("foo", "bar", 1)
tm.get("foo", 1)    →  "bar"
tm.get("foo", 3)    →  "bar"   (latest value at or before 3)
tm.set("foo", "bar2", 4)
tm.get("foo", 4)    →  "bar2"
tm.get("foo", 5)    →  "bar2"
tm.get("foo", 0)    →  ""      (nothing stored that early)

Constraints

  • 1 <= key.length, value.length <= 100
  • 1 <= timestamp <= 10^7
  • The timestamps passed to set are strictly increasing.
  • At most 2 * 10^5 calls to set and get in total.