loopprep

Transactional Key-Value Store

total 00:00
Hard45 min Asked at AnthropicOpenAI
  1. Step 1 · Get, set, delete, count 00:00
  2. Step 2 Locked
  3. Step 3 Locked
  4. Step 4 Locked

Grow a plain dictionary into a store with value counts, expiring keys, nested transactions and atomic conditional batches.

Step 1 — Get, set, delete, count

Build the core store. Every method takes a now argument — an integer clock in seconds that is non-decreasing across calls. Ignore it for this step; later steps need it.

class Store:
    def set(self, key, value, now=0) -> None
    def get(self, key, now=0) -> value | None
    def delete(self, key, now=0) -> bool
    def count(self, value, now=0) -> int

Rules:

  • get returns None for a key that is not present.
  • delete removes the key and returns True, or returns False if it was not there.
  • count(value) returns how many keys currently hold exactly that value.
  • count is called far more often than set; it should not scan the whole store.
s = Store()
s.set("a", 10)
s.set("b", 10)
s.count(10)     # 2
s.set("a", 20)
s.count(10)     # 1
s.delete("b")   # True
s.delete("b")   # False
s.get("b")      # None