In-Memory Store with Transaction Layering
Data Structure DesignAuto-graded · 20 test casesLast updated
Implement an in-memory key-value database supporting GET, SET, DELETE, and nested transaction semantics (BEGIN, ROLLBACK, COMMIT).
Design and implement a system that simulates an in-memory key-value database processing a list of commands. The database supports data mutation, point-in-time reads, and nested transaction contexts.
Command Specifications
Commands are provided as single space-separated string instructions.
Data Commands:
SET <key> <value>: Sets the value of<key>to<value>.GET <key>: Reads the current value of<key>. If the key is not currently present in the database, it produces the string"NULL".DELETE <key>: Removes<key>from the database. If<key>does not exist, this command has no effect.
Transaction Commands:
BEGIN: Opens a new transaction frame. Transactions can be nested arbitrarily deep.ROLLBACK: Reverts all mutations made within the innermost open transaction frame and closes that frame. If no transaction frame is currently open, it produces the string"NO TRANSACTION".COMMIT: Permanently applies all mutations across all currently open transaction frames and closes all open frames. If no transaction frame is currently open, it produces the string"NO TRANSACTION".
Rules & State Behavior
- Operations take effect immediately; a
GETcommand must reflect all previous non-rolled-back data commands (including modifications within any active transaction block). - Deleting a key that does not exist inside a transaction must still record its absent state for that transaction layer (so rolling back will restore it to absent, rather than leaving later modifications).
COMMITorROLLBACKwhen no transactions are open must append"NO TRANSACTION"to the output and alter no data state.- The output list must contain the strings generated in order by all
GETcommands and any"NO TRANSACTION"messages triggered by invalidROLLBACKorCOMMITinstructions.
Constraints
- $1 \le \text{len(commands)} \le 10^5$
- Keys and values are non-empty strings without whitespace (up to 32 characters in length).
- Transaction nesting depth can be up to $10^4$.
- Data queries (
GET) and mutations (SET) should execute in $O(1)$ expected time. Copying the full state of the database onBEGINis not allowed.
Examples
Example 1
Input: process(['SET a 10', 'GET a', 'BEGIN', 'SET a 20', 'GET a', 'BEGIN', 'DELETE a', 'GET a', 'ROLLBACK', 'GET a', 'COMMIT', 'GET a', 'ROLLBACK'])
Output: ['10', '20', 'NULL', '20', '20', 'NO TRANSACTION']
Example 2
Input: process(['GET missing', 'BEGIN', 'SET x one', 'BEGIN', 'SET x two', 'COMMIT', 'GET x', 'ROLLBACK'])
Output: ['NULL', 'two', 'NO TRANSACTION']
Hints
Hint 1
Maintaining layered dictionary masks forces GET operations to traverse up to transaction_depth dictionaries, which exceeds time limits.
Hint 2
Instead of overlaying frames for reads, maintain a single live dictionary and log undo operations in a stack of dictionaries (one per open transaction frame).
Hint 3
In an active transaction frame, only record a key's state the first time it is modified within that frame. Use a unique sentinel object to represent keys that were previously missing.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maintain $O(1)$ expected time for GET and SET operations without cloning the database on every BEGIN:
- Live Main Storage: A single dictionary (
main_db) holds the active state of all keys. EveryGETcommand directly queriesmain_dbin $O(1)$ average time. - Undo Log Stack: A stack (
tx_stack) of hash maps represents active transaction frames. Each map acts as an undo log for its respective transaction level, mappingkey -> value_before_first_touch_in_this_level. - First-Touch Logging: When a
SETorDELETEoperation occurs while at least one transaction is open (tx_stackis non-empty), we check if the targeted key has already been logged in the active transaction frame (tx_stack[-1]). If not present, we log its pre-mutation state frommain_db(or a sentinel object_ABSENTif the key did not exist). - Rollback Handling: Popping the top log off
tx_stackallows us to iterate through logged keys and restore their prior states inmain_db. - Commit Handling: Since changes are applied directly to
main_dbas commands execute, committing simply requires clearingtx_stack.
Complexity Analysis
-
Time Complexity:
GET: $O(1)$ average time.SET/DELETE: $O(1)$ average time.BEGIN: $O(1)$ time to push an empty log dictionary.ROLLBACK: $O(K)$ time, where $K$ is the number of distinct keys modified in the rolled-back block.COMMIT: $O(1)$ time to clear the transaction stack.- Overall time complexity for $N$ total commands is $O(N)$ amortized.
-
Space Complexity: $O(U + T \cdot K)$ auxiliary space, where $U$ is the number of active key-value pairs in
main_dband $T \cdot K$ is the sum of logged entries across all open transaction frames.
Python Reference Solution
from typing import List
_ABSENT = object()
def process(commands: List[str]) -> List[str]:
main_db = {}
tx_stack = []
results = []
for line in commands:
parts = line.split()
op = parts[0]
if op == "SET" or op == "DELETE":
key = parts[1]
if tx_stack:
current_log = tx_stack[-1]
if key not in current_log:
current_log[key] = main_db.get(key, _ABSENT)
if op == "SET":
main_db[key] = parts[2]
else:
main_db.pop(key, None)
elif op == "GET":
key = parts[1]
results.append(main_db.get(key, "NULL"))
elif op == "BEGIN":
tx_stack.append({})
elif op == "ROLLBACK":
if not tx_stack:
results.append("NO TRANSACTION")
else:
undo_log = tx_stack.pop()
for key, old_val in undo_log.items():
if old_val is _ABSENT:
main_db.pop(key, None)
else:
main_db[key] = old_val
elif op == "COMMIT":
if not tx_stack:
results.append("NO TRANSACTION")
else:
tx_stack.clear()
return results