progress

~/problems / Stateful stores / Time-travel key-value store

The value as of time t

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A key's history is two parallel lists: times (strictly increasing) and values, where values[i] was written at times[i] and stayed current until the next write.

Write value_at(times: list[int], values: list[str], t: int) -> str | None: the value written at the latest time <= t, or None if nothing was written by then.

times  = [1, 4, 9]
values = ["red", "green", "blue"]
value_at(times, values, 5)   # "green"  (written at 4, still current at 5)
value_at(times, values, 4)   # "green"  (a write at exactly t counts)
value_at(times, values, 0)   # None     (before the first write)
value_at(times, values, 50)  # "blue"

Up to 100,000 entries; timestamps may be negative; the lists may be empty.

⭐ Bonus: scanning the list each time still passes; a speed test with 300 queries on a 100,000-write history earns a star if you binary search with bisect (O(log n) per query).

Show hint

i = bisect.bisect_right(times, t) counts the writes at or before t, so the answer is values[i - 1] when i > 0.

Topic: Time-travel key-value store. Per-key sorted history + binary search on timestamp.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc