CodeArchon

mediumBinary SearchGoogle

Timeline Snapshot Store

A key-value store records writes with timestamps. A read at time t returns the value from the latest write at time ≤ t.

Implement `set(key, value, timestamp)` and `get(key, timestamp)`. Writes arrive in non-decreasing timestamp order. `get` returns the newest value with timestamp ≤ given.

Choose approach

Maphistory[foo]
0→t=1, v=bar
1/16
Narrationstep 1 of 16

set("foo", "bar", 1) → append (1, "bar") to this key's history.

1class TimelineSnapshotStore:
2 def __init__(self):
3 self.m: dict[str, list[tuple[int, str]]] = {}
4 def set(self, key: str, value: str, timestamp: int) -> None:
5 self.m.setdefault(key, []).append((timestamp, value))
6 def get(self, key: str, timestamp: int) -> str:
7 arr = self.m.get(key, [])
8 lo, hi, ans = 0, len(arr) - 1, ""
9 while lo <= hi:
10 mid = (lo + hi) // 2
11 if arr[mid][0] <= timestamp:
12 ans = arr[mid][1]
13 lo = mid + 1
14 else:
15 hi = mid - 1
16 return ans
Variables
op=set(foo,bar,1)
size=1

How to think about it

  1. set: append — amortized O(1).
  2. get: list is sorted; binary-search for predecessor of the query timestamp.
  3. Track the best valid candidate as you go right whenever the midpoint is still ≤ target.
  4. No match → return "".

Edge cases to catch in interview

  • Unknown key → "".
  • Query before any write for that key → "".
  • Multiple keys share the same timestamps — isolated per key.

Examples

Example 1"bar", "bar", "bar2", "bar2"
{"ops":[["set","foo","bar",1],["get","foo",1],["get","foo",3],["set","foo","bar2",4],["get","foo",4],["get","foo",5]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed