Simple Bank Operations
Problem statement
Process deposit, withdrawal and transfer operations for bank accounts numbered from 1 through balances.length. Account a starts with balances[a - 1] units.
For this exercise, assume each row of operations is [kind, account, other, money]:
kind = 0: depositmoneyintoaccount. The unusedotheris0.kind = 1: withdrawmoneyfromaccount. The unusedotheris0.kind = 2: transfermoneyfromaccounttoother.
An operation fails if any account it uses does not exist. A withdrawal or transfer also fails if the source account has less than money. On failure, change no balance. A valid operation with zero money succeeds. A transfer to the same account checks the balance but leaves it unchanged.
Return one boolean success value for each operation, in order. Use each successful update when processing later operations. Keep both input arrays unchanged.
For this exercise, assume the list is the committed serial order. Follow-up: explain how to preserve these atomic success and failure rules for concurrent callers, and compare locking choices. The returned list does not simulate thread scheduling.
Function
bankOperations(balances: long[], operations: int[][]) → boolean[]Examples
Example 1
balances = [10,5]operations = [[2,1,2,7],[1,1,0,4],[0,1,0,1],[1,1,0,4]]return = [true,false,true,true]The transfer leaves balances [3,12]. Withdrawing 4 then fails and changes nothing. Depositing 1 raises the first balance to 4, so the final withdrawal succeeds and leaves [0,12].
Example 2
balances = [0]operations = [[2,1,1,1],[0,1,0,0],[1,0,0,0],[2,1,2,0]]return = [false,true,false,false]The self-transfer fails for insufficient funds. A zero deposit into account 1 succeeds. Account 0 and recipient account 2 do not exist, so the final two operations fail even though their amounts are zero.
Example 3
balances = [7]operations = []return = []There are no operations, so there are no success values.
Constraints
- For this exercise, assume
1 <= balances.length <= 1000. - For this exercise, assume
0 <= balances[i] <= 1000000000000. - For this exercise, assume
0 <= operations.length <= 1000. - Every operation has exactly
4integer entries. Every entry is between0and1000000000. - For this exercise, assume
kindis0,1or2; both account fields are between0and1001; and0 <= money <= 1000000000. A non-transfer hasother = 0.