~/problems / Stateful stores / In-memory database

OA: In-memory database

medium 5 levels ~90 min Anthropic

Level 1 Records, fields and conditional writes

Build InMemoryDB: a store of records (named by a string key), each record being a map from field name to string value. Every method takes a timestamp first; timestamps are strictly increasing across calls. You won't need them until level 3, but accept them now.

  • set(timestamp, key, field, value) -> None: write the field, creating the record if needed. Overwrites any old value.
  • get(timestamp, key, field) -> str | None: the field's value, or None if the record or field is missing.
  • delete(timestamp, key, field) -> bool: remove the field; True if it was there, False otherwise.
  • compare_and_set(timestamp, key, field, expected, new_value) -> bool: only if the field currently exists and equals expected, change it to new_value and return True. Otherwise change nothing and return False.
  • compare_and_delete(timestamp, key, field, expected) -> bool: the same check, but remove the field on a match.
db = InMemoryDB()
db.set(1, "cfg", "mode", "fast")
db.compare_and_set(2, "cfg", "mode", "slow", "x")     # False (value is "fast")
db.compare_and_set(3, "cfg", "mode", "fast", "safe")  # True
db.compare_and_delete(4, "cfg", "mode", "safe")       # True
db.get(5, "cfg", "mode")                              # None
db.delete(6, "cfg", "mode")                           # False

This is a multi-level problem in the CodeSignal style: each level extends the same class. Later levels add scans, TTLs, backups and history lookups, so pick a data model that will stretch.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

Level 5 unlocks when level 4 passes.

Topic: In-memory database. CRUD with fields, range scans, TTL expiry, time-travel reads.

0:00
Ctrl ' run · Ctrl ↵ submit
esc