Execute Banking Operations with Transaction History
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests command-pattern operation execution, input validation, atomic state transitions, and maintaining per-entity audit logs.
You are given a sequence of banking operations to execute against an in-memory account ledger. Each operation is specified by a command name and a list of arguments. Process all operations in order and return the result of each.
Operations
open_account(account_id)
- Creates a new account with the given identifier and zero balance
- Returns
Trueif successful - Returns
Falseif an account with that identifier already exists
deposit(account_id, amount)
- Adds
amountto the specified account's balance - Returns
Trueif successful - Returns
Falseif the account does not exist or the amount is invalid
withdraw(account_id, amount)
- Subtracts
amountfrom the specified account's balance - Returns
Trueif successful - Returns
Falseif the account does not exist, the amount is invalid, or insufficient funds are available
transfer(source_id, destination_id, amount)
- Moves
amountfrom the source account to the destination account atomically - Returns
Trueif successful - Returns
Falseif either account does not exist, the accounts are identical, the amount is invalid, or the source has insufficient funds
balance(account_id)
- Returns the current balance as an integer
- Returns
Noneif the account does not exist
history(account_id)
- Returns a list of transaction records in chronological order
- Each deposit creates a record:
{"type": "deposit", "amount": <value>} - Each withdrawal creates a record:
{"type": "withdraw", "amount": <value>} - Each transfer creates two records:
- On the source:
{"type": "transfer", "amount": <value>, "direction": "out", "counterparty": <dest_id>} - On the destination:
{"type": "transfer", "amount": <value>, "direction": "in", "counterparty": <source_id>}
- On the source:
- Returns
Noneif the account does not exist - Failed operations do not create history records
Amount Validation
An amount is valid if and only if it is a positive integer (type int, not bool, greater than zero).
Constraints
- 1 ≤ number of operations ≤ 1000
- Account identifiers are non-empty strings
- All amounts fit in a 32-bit signed integer
- Operations are processed sequentially; each sees the state resulting from all prior operations
- Failed operations leave account balances and histories unchanged
Examples
Example 1
Input: execute_banking_operations(['open_account', 'deposit', 'withdraw', 'balance'], [['alice'], ['alice', 1000], ['alice', 250], ['alice']])
Output: [True, True, True, 750]
Example 2
Input: execute_banking_operations(['open_account', 'open_account', 'deposit', 'withdraw', 'withdraw', 'balance'], [['a'], ['a'], ['a', 50], ['a', 20], ['a', 40], ['a']])
Output: [True, False, True, True, False, 30]
Example 3
Input: execute_banking_operations(['open_account', 'open_account', 'deposit', 'transfer', 'balance', 'balance', 'history', 'history'], [['alice'], ['bob'], ['alice', 100], ['alice', 'bob', 35], ['alice'], ['bob'], ['alice'], ['bob']])
Output: [True, True, True, True, 65, 35, [{'type': 'deposit', 'amount': 100}, {'type': 'transfer', 'amount': 35, 'direction': 'out', 'counterparty': 'bob'}], [{'type': 'transfer', 'amount': 35, 'direction': 'in', 'counterparty': 'alice'}]]
Hints
Hint 1
Track both balances and transaction logs in separate data structures, initializing both when an account opens.
Hint 2
For transfers, verify all preconditions before modifying any state, then update both accounts and both histories as a single atomic step.
Hint 3
Amount validation must reject booleans explicitly since in Python, bool is a subclass of int.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain two dictionaries: one tracking current balances and another storing transaction history lists. For each operation, validate all preconditions before modifying state, ensuring failed operations leave the system unchanged.
Key Design Decisions
Amount validation: Check that the value is an integer (but not a boolean, since bool is a subclass of int in Python) and positive.
Atomicity: For transfers, verify that both accounts exist, they differ, the amount is valid, and the source has sufficient funds—all before updating any state. Then update both balances and append to both transaction logs as a single logical step.
History format: Deposits and withdrawals record only their type and amount. Transfers record additional metadata: direction ("in" or "out") and the counterparty account identifier, allowing reconstruction of the full transaction from either side.
Query operations: balance and history return None for nonexistent accounts rather than raising exceptions, matching the pattern of returning status values.
Why It Works
The solution processes operations sequentially, with each operation seeing the cumulative effect of all prior operations. By validating all conditions before any mutation, we guarantee that a failed operation never partially completes. Transaction logs are append-only and synchronized with balance changes, so history always reflects actual state transitions.
Complexity
- Time: O(n) where n is the number of operations, since each operation executes in constant time (dictionary lookups, arithmetic, and list appends are O(1) amortized)
- Space: O(a + t) where a is the number of accounts created and t is the total number of successful transactions recorded in all histories
from typing import List
def execute_banking_operations(operations, arguments):
balances = {}
transaction_logs = {}
results = []
def is_valid_amount(value):
return isinstance(value, int) and not isinstance(value, bool) and value > 0
for op, args in zip(operations, arguments):
if op == "open_account":
acc_id = args[0]
if acc_id in balances:
results.append(False)
else:
balances[acc_id] = 0
transaction_logs[acc_id] = []
results.append(True)
elif op == "deposit":
acc_id, amt = args
if acc_id not in balances or not is_valid_amount(amt):
results.append(False)
else:
balances[acc_id] += amt
transaction_logs[acc_id].append({"type": "deposit", "amount": amt})
results.append(True)
elif op == "withdraw":
acc_id, amt = args
if (acc_id not in balances or not is_valid_amount(amt)
or balances[acc_id] < amt):
results.append(False)
else:
balances[acc_id] -= amt
transaction_logs[acc_id].append({"type": "withdraw", "amount": amt})
results.append(True)
elif op == "transfer":
src, dst, amt = args
if (src not in balances or dst not in balances
or src == dst or not is_valid_amount(amt)
or balances[src] < amt):
results.append(False)
else:
balances[src] -= amt
balances[dst] += amt
transaction_logs[src].append({
"type": "transfer",
"amount": amt,
"direction": "out",
"counterparty": dst,
})
transaction_logs[dst].append({
"type": "transfer",
"amount": amt,
"direction": "in",
"counterparty": src,
})
results.append(True)
elif op == "balance":
acc_id = args[0]
results.append(balances.get(acc_id))
elif op == "history":
acc_id = args[0]
results.append(list(transaction_logs[acc_id]) if acc_id in transaction_logs else None)
else:
results.append(False)
return results