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, ornullif 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. Returnstrue, orfalseif no transaction is open.rollback()discards the innermost open transaction and all changes made in it. Returnstrue, orfalseif 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.