Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Every operation touches at most two balances, so direct indexed storage is sufficient. The important invariant is that an invalid transaction changes nothing: validate account existence and available funds before making any updates.
Approach
Store balances in account-number order, converting the positive one-based account arguments to zero-based indices. Deposits require an existing account. Withdrawals also require enough balance. Transfers validate both accounts and the source funds before subtracting from one and adding to the other. Return false without mutation when a check fails, otherwise perform the update and return true. The constraints guarantee positive account arguments; the code checks their upper bounds. JavaScript uses exact integers for large balances.
class Bank:
def __init__(self, balance: List[int]):
self.acc = balance
def transfer(self, account1: int, account2: int, money: int) -> bool:
if account1 > len(self.acc) or account2 > len(self.acc):
return False
if self.acc[account1 - 1] < money:
return False
self.acc[account1 - 1] -= money
self.acc[account2 - 1] += money
return True
def deposit(self, account: int, money: int) -> bool:
if account > len(self.acc):
return False
self.acc[account - 1] += money
return True
def withdraw(self, account: int, money: int) -> bool:
if account > len(self.acc):
return False
if self.acc[account - 1] < money:
return False
self.acc[account - 1] -= money
return TrueComplexity analysis
Let n = balance.length. Python construction takes O(1) time by retaining the supplied array. JavaScript construction takes O(n) time and auxiliary space to convert balances to exact BigInt integers. Each transaction takes O(1) time and auxiliary space under the bounded integer sizes in the constraints; persistent state stores O(n) balances.
