Skip to content
Onsite

Key-Value Store with Transactions

MediumP2Coding

Design an in-memory key-value store with nested transactions.

Implement the KVStore class (keys and values are strings):

  • set(key, value) stores a value.
  • get(key) returns the value, or null if the key does not exist.
  • delete(key) removes the key (nothing happens if it does not exist).
  • begin() opens a new transaction. Transactions nest.
  • commit() merges the innermost open transaction into its parent: the changes become part of the enclosing transaction, or of the store itself if it was the outermost. Returns true, or false if no transaction is open.
  • rollback() discards the innermost open transaction and all changes made in it. Returns true, or false if no transaction is open.

Reads inside a transaction see its own changes, then those of enclosing transactions, then the store. A change made in an inner transaction is invisible to the outer one until the inner one commits.

Example 1

Input
["KVStore","set","begin","set","get","rollback","get","rollback"] [[],["a","1"],[],["a","2"],["a"],[],["a"],[]]
Output
[null,null,null,null,"2",true,"1",false]
Why
The rollback undoes the set made inside the transaction.

Constraints

  • Keys and values: 1 to 20 characters.
  • Nesting depth <= 1000.
  • At most 10^4 calls.

Hints

Run checks the 2 visible tests, Submit all 9.