773. Build an in-memory key-value store with nested transactions
Many serving systems keep small pieces of state, such as feature flags or routing config, in an in-memory key-value store. Changes are often grouped into transactions so a half-finished update can be thrown away.
Write run_kv(ops). ops is a list of command strings. Keys and values are strings without spaces. The commands are:
SET k v stores v under k. GET k outputs the value, or NULL if k is missing. DELETE k removes k (no output, even if k is missing). COUNT v outputs how many keys currently hold value v, as an int.
BEGIN opens a new transaction. Transactions can nest. ROLLBACK throws away every change made since the most recent BEGIN and closes that transaction. COMMIT closes the most recent transaction and keeps its changes, folding them into the transaction around it (or into the main store if it was the outermost one). If there is no open transaction, ROLLBACK and COMMIT output NO TRANSACTION.
Return the list of outputs in order. Only GET, COUNT and the NO TRANSACTION errors produce output.
def run_kv(ops)Example 1
Input: run_kv(['SET a 10', 'BEGIN', 'SET a 20', 'GET a', 'ROLLBACK', 'GET a'])
Output: ['20', '10']
Example 2
Input: run_kv(['BEGIN', 'SET x 1', 'BEGIN', 'DELETE x', 'COMMIT', 'GET x', 'ROLLBACK', 'GET x', 'COMMIT'])
Output: ['NULL', 'NULL', 'NO TRANSACTION']
Constraints
- Up to 10,000 commands.
- Nesting depth up to 100.
- Values are compared as strings.
Hint 1
Start with SET, GET and DELETE on one dict, then add the stack.
Hint 2
Use a sentinel object for deletes inside a transaction.
Hint 3
COMMIT should merge the top layer into the one below it, not straight into the main store.
Common mistakes
- Committing straight into the main store, which breaks an outer ROLLBACK.
- Removing a key in a transaction layer instead of marking it deleted, so an older value reappears.
- Copying the whole store on every BEGIN, which works but costs O(n) per transaction.
Understand the idea
Layered writes: each transaction is a dict of pending changes on top of the committed state, and reads resolve from the top layer down.