I store the balances in a zero-indexed Python list but treat account numbers as 1-indexed. For every operation I first check that the account indices are within [1, n]. For withdraw and transfer I additionally check that the source account has enough balance. All updates are done in-place, and each operation runs in constant time.
class Bank:
def __init__(self, balance: List[int]):
self.balance = balance
def _valid(self, account: int) -> bool:
return 1 <= account <= len(self.balance)
def transfer(self, account1: int, account2: int, money: int) -> bool:
if not (self._valid(account1) and self._valid(account2)):
return False
i, j = account1 - 1, account2 - 1
if self.balance[i] < money:
return False
self.balance[i] -= money
self.balance[j] += money
return True
def deposit(self, account: int, money: int) -> bool:
if not self._valid(account):
return False
self.balance[account - 1] += money
return True
def withdraw(self, account: int, money: int) -> bool:
if not self._valid(account):
return False
i = account - 1
if self.balance[i] < money:
return False
self.balance[i] -= money
return True- Time: O(1)
- Space: O(1)