Time Based Key-Value Store

Medium Design

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

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Design

All Design problems