progress

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

Library display shelves over time

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

easy ~15 min

Library display shelves feature one book at a time, and staff log every change.

Implement class ShelfLog:

  • put(shelf, book, t): from time t on, shelf features book.
  • clear(shelf, t): from time t on, shelf is empty.
  • at(shelf, t) -> str | None: the book from the latest put/clear on that shelf at or before t; None if that was a clear or there's no change yet.
  • featured(shelf, t1, t2) -> list[str]: every book featured at any moment in [t1, t2], in put order: the book at t1 (if any), then every put with t1 < time <= t2. Repeats count.

Each put/clear has a time strictly greater than all earlier ones. Queries may ask about any time, even negative.

log = ShelfLog()
log.put("window", "Dune", 10)
log.put("window", "Emma", 20)
log.clear("window", 30)
log.put("window", "Dune", 40)
log.at("window", 25)               # "Emma"
log.at("window", 35)               # None     (cleared at 30)
log.at("window", 5)                # None     (nothing yet)
log.featured("window", 15, 40)     # ["Dune", "Emma", "Dune"]
log.featured("window", 30, 39)     # []       (empty the whole time)
log.featured("lobby", 0, 100)      # []

⭐ Bonus: scanning a shelf's history per query still passes; a speed test with 100,000 changes and 100,000 queries earns a star at O(log n) per at (plus the answer's size for featured).

Show hint

per shelf, keep change times and a parallel list of books (None for a clear) and use bisect_right; featured is a slice from the change in effect at t1.

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