In-Memory Store with Nested Transaction Support
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests your ability to implement layered state management with nested scopes, tombstone deletion tracking, and atomic commit/rollback semantics.
In-Memory Store with Nested Transaction Support
Implement a function that simulates an in-memory key-value store supporting nested transactions. The store must handle reads, writes, deletions, and transaction boundaries (begin, commit, rollback) while maintaining correct visibility across transaction layers.
You will receive two parallel lists:
operations: a list of operation names ("put","get","delete","begin","commit","rollback")arguments: a list wherearguments[i]contains the parameters foroperations[i]
Your function must process each operation in sequence and return a list of results. Most operations return None, but get returns the current value for a key (or None if the key doesn't exist or has been deleted).
Operation Specifications
put
- Arguments:
[key, value] - Behavior: Store
valueunderkey. If a transaction is active, the change is scoped to the current transaction layer. - Returns:
None
get
- Arguments:
[key] - Behavior: Retrieve the value for
key. The lookup must respect transaction scope: check the innermost active transaction first, then parent transactions, finally the base store. - Returns: The associated value, or
Noneif the key is absent or deleted in the visible scope.
delete
- Arguments:
[key] - Behavior: Mark
keyas deleted. Within a transaction, this hides the key fromgetoperations but does not affect parent scopes until committed. - Returns:
None
begin
- Arguments:
[] - Behavior: Open a new transaction scope. Changes made after this point are isolated until committed or rolled back.
- Returns:
None
commit
- Arguments:
[] - Behavior: Merge all changes from the current transaction scope into its parent scope (or into the base store if no parent exists). If no transaction is active, this is a no-op.
- Returns:
None
rollback
- Arguments:
[] - Behavior: Discard all changes made in the current transaction scope, restoring visibility to the parent scope. If no transaction is active, this is a no-op.
- Returns:
None
Constraints
1 <= len(operations) <= 10^4- Keys and values can be any hashable type (typically strings or integers)
- Transaction nesting depth will not exceed 100 levels
- Operations will only be the six types listed above
- A
geton a deleted key must returnNone, not an error commitandrollbackwith no active transaction must be handled gracefully (no-op behavior)
Examples
Example 1
Input: transactional_kv_store(['put', 'begin', 'put', 'get', 'rollback', 'get'], [['a', 1], [], ['a', 2], ['a'], [], ['a']])
Output: [None, None, None, 2, None, 1]
Example 2
Input: transactional_kv_store(['put', 'begin', 'put', 'begin', 'delete', 'get', 'commit', 'get', 'commit', 'get'], [['x', 1], [], ['x', 2], [], ['x'], ['x'], [], ['x'], [], ['x']])
Output: [None, None, None, None, None, None, None, None, None, None]
Hints
Hint 1
Think of each transaction as a layer of changes stacked on top of the base store. Reads should search from the top layer downward.
Hint 2
How can you represent a deletion within a transaction layer without actually removing the key from parent layers? Consider using a sentinel value that acts as a marker.
Hint 3
When committing, you only need to merge one layer upward. Use dictionary update to efficiently transfer all changes from the child scope into its immediate parent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: In-Memory Store with Nested Transaction Support
Approach
The core insight is to model transactions as a stack of delta layers. Each layer records only the changes made within that transaction scope, rather than copying the entire store.
Data structures:
base_store: a dictionary holding all committed key-value pairstransaction_stack: a stack (list) of dictionaries, one per active transaction- Each transaction layer stores only keys modified in that scope
Operation implementation:
-
Write operations (
put,delete): Always target the topmost transaction layer if one exists, otherwise write directly tobase_store. -
Read operation (
get): Walk the stack from top to bottom. Return the first entry found. If no transaction contains the key, checkbase_store. -
Delete handling: Store a unique sentinel object (
_DELETED = object()) as the value. This marker shadows any value in parent layers. Whengetencounters this sentinel, it returnsNone. -
begin: Push an empty dictionary onto the stack. -
commit: Pop the top layer and merge it into the parent layer (orbase_storeif at root level) using dictionary update. -
rollback: Simply pop and discard the top layer.
Why This Works
Visibility semantics: The stack search ensures inner transactions see their own changes first, then parent changes, matching the required scope rules.
Deletion correctness: Using a sentinel prevents a deleted key from "falling through" to a parent's value. The sentinel is a unique object instance that cannot collide with user data (unlike None, which might be a legitimate stored value).
Atomicity: Commit and rollback affect exactly one layer. Rolling back discards all changes in that scope without touching parent state. Committing merges one level upward, preserving isolation until explicitly committed to the root.
Edge cases:
- Deleting a nonexistent key simply stores a tombstone (harmless)
- Committing or rolling back with no active transaction is safely ignored
- Nested deletions work correctly because tombstones propagate upward only on commit
Complexity
Let d = maximum nesting depth, k = keys touched in a transaction scope, n = total operations.
Time:
put/delete/begin/rollback: O(1)get: O(d) — worst case scans all layerscommit: O(k) — merges one layer's keys- Overall for n operations: O(n × d)
Space: O(K + T) where K is the total unique keys ever stored and T is the sum of keys touched across all active transaction layers. Each layer stores only modified keys, not full snapshots.
Implementation
from typing import List
_DELETED = object()
def transactional_kv_store(operations: List[str], arguments: List[List]) -> List:
base_store = {}
transaction_stack = []
results = []
for op, args in zip(operations, arguments):
if op == "put":
key, value = args
current_layer = transaction_stack[-1] if transaction_stack else base_store
current_layer[key] = value
results.append(None)
elif op == "get":
key = args[0]
found = False
result_value = None
for layer in reversed(transaction_stack):
if key in layer:
found = True
result_value = layer[key]
break
if not found and key in base_store:
found = True
result_value = base_store[key]
results.append(None if not found or result_value is _DELETED else result_value)
elif op == "delete":
key = args[0]
current_layer = transaction_stack[-1] if transaction_stack else base_store
current_layer[key] = _DELETED
results.append(None)
elif op == "begin":
transaction_stack.append({})
results.append(None)
elif op == "commit":
if transaction_stack:
top_layer = transaction_stack.pop()
parent_layer = transaction_stack[-1] if transaction_stack else base_store
parent_layer.update(top_layer)
results.append(None)
elif op == "rollback":
if transaction_stack:
transaction_stack.pop()
results.append(None)
else:
raise ValueError(f"Unknown operation: {op}")
return results