Nested Undo-Log Session Store with Value Tallies
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate an in-memory key-value store with nested transactions, a global commit, and a live per-value key tally, processing a batch of operations and returning each result.
Nested Undo-Log Session Store with Value Tallies
You are simulating a small in-memory database that maps string keys to scalar values and supports nested transactions. You are given a batch of commands. Process them in order and report one result per command.
Input
operations: a list of command names. Each is one of"set","get","count","begin","commit","rollback".arguments: a list of the same length.arguments[i]is the list of arguments foroperations[i].
Commands
| Command | Arguments | Effect | Result |
|---|---|---|---|
set | [key, value] | Map key to value, replacing any previous value. | None |
get | [key] | Look up the value currently visible for key. | The value, or None if the key does not exist. |
count | [value] | Count the keys whose currently visible value equals value. | The integer count (0 if none). |
begin | [] | Open a new transaction, nested inside any transaction already open. | None |
commit | [] | Make permanent the changes of all currently open transactions and close all of them. | None |
rollback | [] | Undo every change made since the most recent still-open begin, and close only that transaction. | None |
Rules
- The visible state always includes uncommitted changes made in open transactions.
getandcountmust reflect it. - Rolling back a transaction restores exactly the state that existed when that transaction began. A key created inside the transaction must be removed again, not left mapped to
None. - Rolling back an inner transaction leaves the changes of the enclosing transactions in place. Those can then be rolled back separately.
- If
commitorrollbackis called while no transaction is open, it does nothing and still returnsNone. - After a
commit, no transactions remain open, so a followingrollbackdoes nothing. - A value may itself be
None. A key mapped toNoneexists, andcount(None)counts such keys.getreturnsNoneboth for a missing key and for a key mapped toNone. - Setting a key to the value it already holds changes no counts.
Output
Return a list with one entry per command, in order, holding the result described in the table.
Constraints
operationsandargumentshave the same length, between 0 and about 10^5.- Keys are strings. Values are hashable scalars (integers, strings,
None, and so on). - Every command comes with the argument list described above.
- The expected running time is close to linear in the number of commands.
Examples
Example 1
Input: run_session_store(['set', 'get', 'count', 'begin', 'set', 'get', 'count', 'rollback', 'get', 'count'], [['a', 10], ['a'], [10], [], ['a', 20], ['a'], [20], [], ['a'], [20]])
Output: [None, 10, 1, None, None, 20, 1, None, 10, 0]
Example 2
Input: run_session_store(['set', 'set', 'begin', 'set', 'begin', 'set', 'count', 'rollback', 'get', 'commit', 'count', 'rollback'], [['a', 1], ['b', 1], [], ['a', 2], [], ['b', 2], [2], [], ['b'], [], [1], []])
Output: [None, None, None, None, None, None, 2, None, 1, None, 1, None]
Example 3
Input: run_session_store(['get', 'count', 'commit', 'rollback', 'begin', 'set', 'set', 'count', 'rollback', 'get', 'count'], [['missing'], [None], [], [], [], ['x', None], ['y', None], [None], [], ['x'], [None]])
Output: [None, 0, None, None, None, None, None, 2, None, None, 0]
Hints
Hint 1
Keep one live dictionary that always holds the currently visible state, so get is a plain lookup. Maintain a second dictionary from value to number of keys and update it on every write.
Hint 2
For each open transaction, keep an undo record that maps a key to the value it had before that transaction first modified it. Use a unique sentinel for 'did not exist' so it differs from a real None value.
Hint 3
Record only the first change to a key per transaction. Rollback pops the top record and restores each key, adjusting the value tallies. Commit just discards all undo records.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Write changes eagerly into one live dictionary, so it always represents the currently visible state. Alongside it, keep a reverse index from each value to the number of keys holding it. Each open transaction owns an undo record.
Data structures:
store: key to current value.tally: value to number of keys holding it. Entries that drop to zero are removed.undo_stack: one dictionary per open transaction, mapping a key to the value it had before that transaction first changed it, or to a uniquemissingsentinel if it did not exist.
Operations:
- set: read the key's old value (or
missing). If a transaction is open and the key is not yet in the top undo record, store the old value there. Then decrement the tally of the old value (if any), write the new value, and increment its tally. - get: plain dictionary lookup, defaulting to
None. - count: look up the tally, defaulting to
0. - begin: push an empty undo record.
- commit: clear the whole undo stack. The data is already in
store, so committing means forgetting how to undo it. With no open transaction this does nothing. - rollback: if the stack is non-empty, pop the top record. For each key, decrement the tally of its current value, then either delete the key (if the saved value is
missing) or restore the saved value and increment its tally. With an empty stack it does nothing.
Why it is correct
The invariant is that store equals the visible state and tally[v] equals the number of keys mapped to v. set and rollback both change the two structures together, so the invariant holds after every command.
Recording only the first old value per key per transaction means the record holds the key's state at the moment the transaction began. Restoring it undoes any number of later writes in that transaction. Because each transaction has its own record and rollback touches only the top one, nested rollbacks restore the correct intermediate states. The sentinel keeps a truly absent key distinct from one mapped to None.
Complexity
set,get,count,begin: O(1) on average.commit: O(open transactions), which is amortized O(1) since each was created by abegin.rollback: O(number of distinct keys changed in that transaction), bounded in total by the number ofsetcommands.- Space: O(keys + distinct values + undo entries).
Reference solution
from typing import List
def run_session_store(operations: List[str], arguments: List[List[object]]) -> List[object]:
store = {}
tally = {}
missing = object()
undo_stack = []
results = []
def bump(value, delta):
new = tally.get(value, 0) + delta
if new == 0:
tally.pop(value, None)
else:
tally[value] = new
def assign(key, value):
old = store.get(key, missing)
if undo_stack:
top = undo_stack[-1]
if key not in top:
top[key] = old
if old is not missing:
bump(old, -1)
store[key] = value
bump(value, 1)
for op, args in zip(operations, arguments):
if op == "set":
assign(args[0], args[1])
results.append(None)
elif op == "get":
results.append(store.get(args[0], None))
elif op == "count":
results.append(tally.get(args[0], 0))
elif op == "begin":
undo_stack.append({})
results.append(None)
elif op == "commit":
undo_stack.clear()
results.append(None)
elif op == "rollback":
if undo_stack:
frame = undo_stack.pop()
for key, old in frame.items():
bump(store[key], -1)
if old is missing:
del store[key]
else:
store[key] = old
bump(old, 1)
results.append(None)
else:
results.append(None)
return results