Nested Transaction Log for an In-Memory Dictionary
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a key-value store with nested begin, commit and rollback by replaying a command list and recording each read result.
You are given a script of commands for a small in-memory key-value store that supports nested transactions. Replay the script from an empty store and report what each command produces.
Commands
Command i is commands[i], and its arguments are in params[i].
| Command | Arguments | Effect |
|---|---|---|
"set" | [key, value] | Store value under key, replacing any existing value. |
"get" | [key] | Read the current value of key. |
"delete" | [key] | Remove key. Deleting a key that does not exist is allowed and changes nothing. |
"begin" | [] | Open a new transaction, nested inside any transaction that is already open. |
"commit" | [] | Close the innermost open transaction and keep its changes. |
"rollback" | [] | Close the innermost open transaction and undo every change made since its matching begin. |
Transaction rules
- Transactions form a stack.
commitandrollbackact only on the innermost open transaction, never on all of them. - Reads inside a transaction see all writes made so far, including writes from enclosing transactions and uncommitted writes.
rollbackrestores each affected key to exactly the state it had when the innermost transaction began. A key that was overwritten gets its old value back. A key that was deleted is restored. A key that did not exist before the transaction is absent again.- Committing a nested transaction does not make its changes permanent. They are handed to the enclosing transaction, so rolling back the enclosing transaction also undoes them.
- Committing a top-level transaction makes its changes permanent.
- If no transaction is open,
commitandrollbackdo nothing.
Output
Return a list with one entry per command, in order.
- For
"get", the entry is the key's current value, orNoneif the key is missing or deleted. - For every other command, the entry is
None.
Constraints
len(commands) == len(params).- Every command is one of
"set","get","delete","begin","commit","rollback", and its argument list has the shape shown above. - Keys are strings and values are integers.
get,set,deleteandbeginshould run in expected constant time.commitandrollbackmay take time proportional to the number of distinct keys changed in the innermost transaction.- The number of commands is small enough for a single linear pass.
Examples
Example 1
Input: simulate_store(['set', 'begin', 'set', 'delete', 'get', 'rollback', 'get'], [['a', 1], [], ['a', 2], ['b'], ['a'], [], ['a']])
Output: [None, None, None, None, 2, None, 1]
Hints
Hint 1
Keep one dictionary for the live data, and a stack of per-transaction undo logs, one dictionary per open transaction.
Hint 2
The first time a transaction touches a key, record what the key held before (or that it was absent). Later writes to the same key in that transaction should not overwrite this record.
Hint 3
On rollback, replay the innermost log: put back old values and remove keys that were absent. On a nested commit, move to the parent log only the entries for keys the parent has not recorded yet, since the parent needs the older state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two structures:
- A dictionary
dataholding the current, live view of the store. All reads and writes go straight to it, soget,setanddeleteare expected O(1). - A stack of undo logs, one dictionary per open transaction. Each log maps a key to the value it held when that transaction first touched the key, or to a special sentinel meaning "the key did not exist".
Writing. Before set or delete changes a key, check whether the innermost log already has an entry for it. If not, record the key's current state (its value or the sentinel). Only the first touch is recorded, because that is the state the transaction started with. Later writes to the same key must not overwrite it.
Rollback. Pop the innermost log and apply it: put old values back, and remove keys whose recorded state is the sentinel. If no transaction is open, do nothing.
Commit. Pop the innermost log. If there is an enclosing transaction, copy into its log each entry whose key it has not recorded yet. The live data already holds the committed values. The parent needs the older state so that its own rollback can still undo these changes. Keys the parent already recorded keep the parent's older record. If the stack becomes empty, the changes are permanent and the log is discarded. If no transaction is open, do nothing.
Why it is correct
At any moment, the log for a transaction holds the state of every key it touched, as of the moment that transaction began. Rolling back restores exactly that state. When a nested transaction commits, its changes become part of the parent's work. The parent's log must then describe every key changed by the parent or any committed child, as of the parent's start. Merging only the missing keys achieves this: a key the parent already recorded has its older state saved, and a key the parent had not touched has the state the child saw, which equals the state at the parent's start.
Complexity
get,set,delete,begin: expected O(1) time.commitandrollback: O(k) time, where k is the number of distinct keys changed in the innermost transaction. This cost is inherent, because each affected key must be merged or restored.- Space: O(n + total distinct keys recorded across open transactions).
Reference solution
from typing import List, Optional
_ABSENT = object()
def simulate_store(commands: List[str], params: List[List]) -> List[Optional[int]]:
data = {}
undo_stack = []
output = []
def remember(key):
# Record the pre-transaction state of key, once per transaction.
if undo_stack and key not in undo_stack[-1]:
undo_stack[-1][key] = data.get(key, _ABSENT)
for cmd, args in zip(commands, params):
if cmd == "get":
output.append(data.get(args[0]))
elif cmd == "set":
key, value = args
remember(key)
data[key] = value
output.append(None)
elif cmd == "delete":
key = args[0]
remember(key)
data.pop(key, None)
output.append(None)
elif cmd == "begin":
undo_stack.append({})
output.append(None)
elif cmd == "commit":
if undo_stack:
log = undo_stack.pop()
if undo_stack:
parent = undo_stack[-1]
for key, old in log.items():
if key not in parent:
parent[key] = old
output.append(None)
elif cmd == "rollback":
if undo_stack:
log = undo_stack.pop()
for key, old in log.items():
if old is _ABSENT:
data.pop(key, None)
else:
data[key] = old
output.append(None)
else:
raise ValueError(f"Unknown operation: {cmd}")
return output