Design an In-Memory Key-Value Engine with Transactions
Data Structure DesignAuto-graded · 23 test casesLast updated
Implement an in-memory key-value database supporting frequency counting and nested transaction rollbacks.
Implement an in-memory key-value database engine that processes a sequence of instructions line by line and returns its output.
The input is provided as a list of command strings commands. The engine supports seven instructions:
SET key value: Setskeytovalue. Updates existing assignments or creates a new entry ifkeywas not present. Produces no output.GET key: Looks upkey. Appendsvalueto the output list if found, or"NULL"ifkeydoes not exist.DELETE key: Removeskeyand its mapped value from the database if present. Ifkeydoes not exist, does nothing. Produces no output in either case.COUNT value: Appends the count of keys currently assigned tovalue(as a decimal string, e.g.,"0","1","2") to the output list.BEGIN: Opens a new nested transaction block. Produces no output.ROLLBACK: Reverts all state modifications made during the most recently opened active transaction. Appends"NO TRANSACTION"to the output list if no transaction is currently open.COMMIT: Makes all modifications across all open transaction blocks permanent and closes all active transactions. Produces no output, even if no transaction is open.
Rules & Details
- Mutation Logging:
SETandDELETEoperations append state changes to an internal change log regardless of whether a transaction is open. This includes executingDELETEon non-existent keys (which logs that the key did not exist before). - Rollback Mechanics: A successful
ROLLBACKpops the innermost transaction scope and undoes all log entries recorded since that scope was opened, applied in reverse chronological (LIFO) order. - Commit Mechanics: A
COMMITcloses all active transaction blocks simultaneously and purges all logged history. SubsequentROLLBACKcommands will output"NO TRANSACTION"unless a new transaction is subsequently opened withBEGIN.
Constraints
- $1 \le \text{len}(commands) \le 100{,}000$
- Keys and values consist of ASCII characters excluding whitespace.
SET,GET,DELETE,COUNT, andBEGINshould operate in $O(1)$ expected time.ROLLBACKshould operate in $O(R)$ time, where $R$ is the number of changes logged in the reverted transaction block.
Output Format
Return a list of strings containing all output values emitted by GET, COUNT, and failed ROLLBACK commands, in the exact sequence they were generated.
Examples
Example 1
Input: execute_commands(['SET a 10', 'GET a', 'COUNT 10', 'DELETE a', 'GET a', 'COUNT 10'])
Output: ['10', '1', 'NULL', '0']
Example 2
Input: execute_commands(['SET a 10', 'BEGIN', 'SET a 20', 'GET a', 'ROLLBACK', 'GET a', 'COUNT 10'])
Output: ['20', '10', '1']
Example 3
Input: execute_commands(['SET a 10', 'BEGIN', 'SET a 20', 'BEGIN', 'SET b 20', 'COUNT 20', 'ROLLBACK', 'GET b', 'GET a', 'COMMIT', 'ROLLBACK'])
Output: ['2', 'NULL', '20', 'NO TRANSACTION']
Example 4
Input: execute_commands(['GET missing', 'ROLLBACK', 'COUNT absent', 'DELETE missing', 'SET x same', 'SET y same', 'COUNT same'])
Output: ['NULL', 'NO TRANSACTION', '0', '2']
Hints
Hint 1
Use two hash maps: one mapping key -> value for direct lookup, and another mapping value -> count to serve COUNT queries in O(1) time.
Hint 2
Instead of copying entire hash maps when BEGIN is executed, append write operations (SET and DELETE) to an undo stack recording (key, existed_flag, old_value).
Hint 3
Track transaction scopes by pushing the current height of the undo stack onto a transaction stack during BEGIN.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To implement the database with $O(1)$ standard operations and efficient transaction rollback without full dataset cloning:
-
Dual Hash Maps for Fast Queries:
values: mapskey -> valueto serveGETrequests in $O(1)$ expected time.counts: mapsvalue -> key_countto keep track of frequency counts forCOUNTqueries in $O(1)$ time. Whenever a key's assigned value changes or is deleted,countsis decremented for the old value and incremented for the new value. Frequency entries reaching 0 are deleted to save memory.
-
Undo Log for Transactions:
- Creating full deep copies of hash maps at every
BEGINtakes $O(N)$ time and memory per transaction. - Instead, we track state mutations (
SETandDELETE) by pushing inverse records(key, previously_existed_bool, old_value)onto anundostack. - A
transactionsstack recordslen(undo)wheneverBEGINis issued, marking the log position where that transaction block began. ROLLBACKpops the inner transaction marker fromtransactionsand unrollsundoentries down to that recorded index, restoring key and count states back to their pre-transaction values.COMMITflushes bothtransactionsandundo, cementing all active changes.
- Creating full deep copies of hash maps at every
Complexity Analysis
-
Time Complexity:
SET,GET,DELETE,COUNT,BEGIN: $O(1)$ expected time.ROLLBACK: $O(R)$ time where $R$ is the number of mutations executed inside the reverted scope. Each logged change is pushed once and unrolled at most once, maintaining $O(1)$ amortized time per operation.COMMIT: $O(1)$ amortized time.- Total time complexity across $N$ commands is $O(N)$.
-
Space Complexity:
- $O(K + U)$ memory, where $K$ is the number of distinct key-value assignments and $U$ is the depth of the undo stack ($U \le N$).
Python Reference Solution
from typing import List
def execute_commands(commands: List[str]) -> List[str]:
values = {}
counts = {}
undo = []
transactions = []
output = []
def set_value(key, value):
existed = key in values
old_value = values.get(key)
undo.append((key, existed, old_value))
if existed:
counts[old_value] -= 1
if counts[old_value] == 0:
del counts[old_value]
values[key] = value
counts[value] = counts.get(value, 0) + 1
def delete_value(key):
existed = key in values
old_value = values.get(key)
undo.append((key, existed, old_value))
if existed:
del values[key]
counts[old_value] -= 1
if counts[old_value] == 0:
del counts[old_value]
def restore(key, existed, old_value):
if key in values:
current = values[key]
counts[current] -= 1
if counts[current] == 0:
del counts[current]
if existed:
values[key] = old_value
counts[old_value] = counts.get(old_value, 0) + 1
else:
values.pop(key, None)
for command in commands:
parts = command.split()
operation = parts[0]
if operation == "SET":
set_value(parts[1], parts[2])
elif operation == "GET":
output.append(values.get(parts[1], "NULL"))
elif operation == "DELETE":
delete_value(parts[1])
elif operation == "COUNT":
output.append(str(counts.get(parts[1], 0)))
elif operation == "BEGIN":
transactions.append(len(undo))
elif operation == "ROLLBACK":
if not transactions:
output.append("NO TRANSACTION")
else:
start = transactions.pop()
while len(undo) > start:
key, existed, old_value = undo.pop()
restore(key, existed, old_value)
elif operation == "COMMIT":
undo.clear()
transactions.clear()
return output