Replay Ledger Commands on a Guarded Account
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate an account that processes a list of deposit, withdraw, balance and history commands, rejecting invalid amounts and overdrafts while recording only successful transactions.
You are given the starting balance of an account and a sequence of commands to run against it, in order. Write a function that processes the commands and returns one result per command.
Commands
Each command has a name and a list of arguments. The i-th entry of operations is paired with the i-th entry of arguments.
| Command | Arguments | Behavior | Result |
|---|---|---|---|
"deposit" | [amount] | If amount > 0, add it to the balance and record a ledger entry {"type": "deposit", "amount": amount}. Otherwise do nothing. | True if applied, False if rejected |
"withdraw" | [amount] | If amount > 0 and amount is not greater than the current balance, subtract it and record a ledger entry {"type": "withdrawal", "amount": amount}. Otherwise do nothing. | True if applied, False if rejected |
"get_balance" | [] | Reads the current balance. | The balance |
"get_transaction_history" | [] | Reads the ledger. | A list of all ledger entries in the order they were recorded |
Rules
- The starting balance is not a ledger entry. The ledger only contains successful deposits and withdrawals.
- A rejected command changes nothing: the balance stays the same and no ledger entry is added.
- Withdrawing exactly the current balance is allowed and leaves a balance of
0. - Note the spelling: the command is
"withdraw", but the ledger entry type is"withdrawal". - The history returned by a command must be a snapshot. Later commands must not alter a snapshot that was already returned.
- If a command name is not one of the four above, raise
ValueError.
Task
Implement the function so that it returns the list of results, one per command, in the same order as the commands.
Constraints
operationsandargumentshave the same length.- Amounts are numbers; zero and negative amounts can appear and must be rejected.
initial_balanceis non-negative.- Commands are executed strictly sequentially in the given order.
Examples
Example 1
Input: replay_account_commands(100, ['deposit', 'withdraw', 'withdraw', 'get_balance', 'get_transaction_history'], [[50], [20], [200], [], []])
Output: [True, True, False, 130, [{'type': 'deposit', 'amount': 50}, {'type': 'withdrawal', 'amount': 20}]]
Example 2
Input: replay_account_commands(0, ['withdraw', 'deposit', 'get_balance', 'get_transaction_history'], [[1], [25], [], []])
Output: [False, True, 25, [{'type': 'deposit', 'amount': 25}]]
Example 3
Input: replay_account_commands(500, ['deposit', 'deposit', 'withdraw', 'get_transaction_history', 'get_balance'], [[100], [50], [200], [], []])
Output: [True, True, True, [{'type': 'deposit', 'amount': 100}, {'type': 'deposit', 'amount': 50}, {'type': 'withdrawal', 'amount': 200}], 450]
Hints
Hint 1
Keep three pieces of state while looping: the balance, the ledger list, and the list of results.
Hint 2
Rejection checks come first: a non-positive amount is rejected, and for withdrawals so is an amount greater than the balance. Rejected commands must not touch the balance or the ledger.
Hint 3
When returning the history, build a new list of copied entries so that later commands cannot change a snapshot you already returned.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the function as a small state machine. Keep the current balance, a ledger of successful transactions, and a list of results. Walk through the commands in order and handle each one:
- deposit: if the amount is positive, increase the balance, append a
"deposit"entry, and reportTrue. Otherwise reportFalseand change nothing. - withdraw: if the amount is positive and no larger than the balance, decrease the balance, append a
"withdrawal"entry, and reportTrue. Otherwise reportFalseand change nothing. - get_balance: report the current balance.
- get_transaction_history: report a new list containing copies of every ledger entry.
- anything else: raise
ValueError.
Why it is correct
- The balance and the ledger are only modified together, inside the branch where the command is accepted. So at every moment the balance equals the initial balance plus the deposits in the ledger minus the withdrawals in the ledger.
- Rejected commands return before touching state, so the ledger holds only successful transactions, as required.
- The withdrawal check uses
amount <= balance, so withdrawing the exact balance is allowed, and the balance can never become negative. - Returning copies of the ledger entries means a snapshot taken earlier is unaffected by later deposits or withdrawals, or by a caller mutating it.
- Commands run strictly in order, so each result reflects exactly the state produced by the commands before it.
Complexity
- Time: O(1) per deposit, withdraw, or balance command. A history command costs O(h), where h is the current ledger size. Overall O(n + total size of all returned snapshots) for n commands.
- Space: O(h) for the ledger plus the size of the returned snapshots.
Reference solution
from typing import List
def replay_account_commands(initial_balance: int, operations: List[str], arguments: List[List]) -> List:
balance = initial_balance
ledger = []
results = []
for operation, args in zip(operations, arguments):
if operation == "deposit":
amount = args[0]
if amount > 0:
balance += amount
ledger.append({"type": "deposit", "amount": amount})
results.append(True)
else:
results.append(False)
elif operation == "withdraw":
amount = args[0]
if amount > 0 and amount <= balance:
balance -= amount
ledger.append({"type": "withdrawal", "amount": amount})
results.append(True)
else:
results.append(False)
elif operation == "get_balance":
results.append(balance)
elif operation == "get_transaction_history":
results.append([entry.copy() for entry in ledger])
else:
raise ValueError("unknown operation")
return results