Time Based Key-Value Store

Medium Design AI round

TimeMap() keeps values under keys, each with the time it was stored, and can say what a key held at any time. It holds nothing to begin with.

set(key, value, timestamp) stores value under key at the time timestamp. Every call to set has a larger timestamp than every call to set before it, whatever their keys.

get(key, timestamp) returns the value of the latest set of key whose time is no later than timestamp. When there is none, because key was never set or was first set after timestamp, it returns the empty string "".

Example 1

Calls:
TimeMap()
set("door", "red", 5)
set("door", "blue", 9)
get("door", 7) → "red"
get("door", 9) → "blue"
get("door", 4) → ""
get("lamp", 9) → ""

At time 7 the latest set of door is the one at time 5, so red; at 9 it is blue, set at exactly 9. Nothing was set under door by time 4, and nothing ever under lamp, so both answer the empty string.

Example 2

Calls:
TimeMap()
set("a", "x1", 2)
set("b", "y1", 3)
set("a", "x2", 10)
get("a", 9) → "x1"
get("b", 100) → "y1"
get("a", 10) → "x2"
get("b", 2) → ""

Example 3

Calls:
TimeMap()
set("k1", "v", 1)
get("k1", 1000000000) → "v"
set("k1", "w", 1000000000)
get("k1", 999999999) → "v"
get("k1", 1000000000) → "w"

Constraints

  • key and value are 1 to 10 characters, each a lowercase English letter or a digit
  • 1 ≤ timestamp ≤ 10⁹
  • each set has a larger timestamp than every set before it
  • at most 8 × 10⁵ calls in all to set and get

Watch the explanation

More Design

  • LRU CacheAI round · Medium
  • Min StackAI round · Medium
  • Find Median from Data StreamHard
  • Serialize and Deserialize Binary TreeHard
  • Insert Delete GetRandom O(1)Medium
All Design problems