codejump
MediumPythonJavaScriptTypeScript

System Design — Time-Based Key-Value Store

System DesignBinary SearchHash Map

A versioned store: every write keeps its history, and a read asks "what was the value at
time T?".

solve(args, ops) builds new TimeMap() and replays ops:

  • set(key, value, timestamp) — store value for key at timestamp. For a given key,

timestamps are strictly increasing across calls. Returns nothing.

  • get(key, timestamp) — return the value stored at the **largest timestamp

<= timestamp** for that key, or "" if there is none (unknown key, or every write is in
the future).

Because the timestamps of a key arrive sorted, each key's history is a sorted array and
get is a binary search (the same "last element <= target" search as in the Searching
path), O(log n).

Example

set("foo","bar",1)   get("foo",1) → "bar"    get("foo",3) → "bar"
set("foo","bar2",4)  get("foo",4) → "bar2"   get("foo",0) → ""

Sample tests

Test #1Classic example
Input: [[],[["set","foo","bar",1],["get","foo",1],["get","foo",3],["set","foo","bar2",4],["get","foo",4],["get","foo",5],["get","foo",0],["get","baz",1]]]
Output: [null,"bar","bar",null,"bar2","bar2","",""]
Test #2Keys are independent
Input: [[],[["set","a","1",10],["set","b","2",5],["get","a",7],["get","b",7],["get","a",10]]]
Output: [null,null,"","2","1"]
Test #3Three versions
Input: [[],[["set","k","v1",1],["set","k","v2",5],["set","k","v3",9],["get","k",4],["get","k",5],["get","k",8],["get","k",100]]]
Output: [null,null,null,"v1","v2","v2","v3"]