KatInterview

Build an In-Memory Store with Nested Transactions and Value Counts

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-maptransactionsundo-log

Last updated

Design a string key-value store with transactional writes, fast rollback, and a count of keys holding a given value, with all transaction semantics spelled out.

Task

Design a single-process, in-memory store that maps string keys to string values. It must support these operations:

  • set(key, value): create or overwrite a key.
  • get(key): return the current value, or a defined "missing" result.
  • delete(key): remove a key.
  • count(value): return how many keys currently hold exactly that value.
  • begin(), commit(), rollback(): transaction control.

Because the requirements do not say how nested transactions behave, you must choose a behavior and state it explicitly.

Assumptions

  • Keys and values are strings.
  • Within a transaction, reads observe that transaction's own earlier writes.
  • count must reflect the state visible to the caller at that moment, including uncommitted changes in the current transaction.
  • Execution is single-threaded unless you are asked about concurrency as a follow-up.
  • Durability is out of scope unless you choose to discuss it.

Questions worth settling up front

  • Can transactions nest? What does committing an inner transaction mean?
  • Is deleting a missing key an error or a no-op?
  • What happens on commit or rollback with no open transaction?
  • What cost do you target for ordinary operations, rollback, and count?

What to cover

  1. Semantics. Define every command, including misses, overwrites, deletes, and what count returns before and after commit or rollback.
  2. Data structures. Choose structures for key lookup, value counting, and reversible changes. Compare a full snapshot per transaction with an undo log or layered writes. Explain how repeated writes to one key inside a transaction are handled.
  3. Testing and extensions. Describe how you would test commits, rollbacks, misses, duplicate values, and misuse. Explain how adding concurrency or persistence would change the design.

Hints

Hint 1

Keep two indexes in sync: a map from key to value and a map from value to the number of keys holding it. Route every mutation through one internal function that updates both.

Hint 2

Do not copy the whole store on begin. Record, for each change, what is needed to reverse it: the key and its previous value, or the fact that it was absent.

Hint 3

To roll back, pop the newest transaction's undo entries and apply them in reverse order using the same internal mutation function, so the counts are repaired automatically.