You need to implement a banking system that manages multiple customer accounts. The system should support three fundamental banking operations: transferring money between accounts, depositing money into an account, and withdrawing money from an account.
Your task is to create a Bank class that is initialized with an array of starting balances for each account. The accounts are numbered starting from 1 (not 0), so the first element in the balance array corresponds to account 1, the second element to account 2, and so on.
Each operation should validate that:
If an operation cannot be completed due to invalid account numbers or insufficient funds, it should return false without modifying any balances. Otherwise, it should perform the operation and return true.
transfer(account1, account2, money) method that moves money from account1 to account2deposit(account, money) method that adds money to the specified accountwithdraw(account, money) method that removes money from the specified accounttrue on success and false on failureExample 1:
` Input: Bank bank = new Bank([100, 200, 300]) bank.withdraw(1, 50) bank.deposit(2, 100) bank.transfer(3, 1, 150)
Output: [true, true, true]
Explanation:
Example 2:
` Input: Bank bank = new Bank([500, 1000]) bank.withdraw(3, 100) bank.deposit(2, 50) bank.transfer(2, 1, 2000)
Output: [false, true, false]
Explanation:
Example 3:
` Input: Bank bank = new Bank([100]) bank.withdraw(1, 100) bank.withdraw(1, 10)
Output: [true, false]
Explanation:
Hint 1: Account Validation Start by creating a helper method to check if an account number is valid. Remember that accounts are 1-indexed, so you'll need to check if the account number is between 1 and the length of the balance array (inclusive).
Hint 2: Handling the 1-indexed Accounts Since accounts are numbered starting from 1, but arrays are 0-indexed, you'll need to convert between the two. Account number
ncorresponds to indexn-1in your balance array.
Hint 3: Operation Order for Transfer For the transfer operation, make sure to check both account validity and sufficient funds before making any changes. Only modify balances if all validations pass. This prevents partial transfers that could corrupt the data.
Full Solution `` Solution Explanation:
The solution maintains an internal list of account balances where the list index corresponds to the account number minus 1 (to handle 1-indexed accounts with 0-indexed arrays).
Key Design Decisions:
Account Validation: A helper method
_is_valid_accountcentralizes the validation logic, checking if an account number falls within the valid range [1, n].Index Conversion: Since accounts are 1-indexed but arrays are 0-indexed, we consistently subtract 1 when accessing the balance array.
Operation Safety: Each operation follows a validate-then-execute pattern:
- First, check if all involved accounts are valid
- For withdraw/transfer, verify sufficient funds exist
- Only if all checks pass, modify the balances
- Return boolean indicating success or failure
Transfer Implementation: The transfer method is essentially a combination of withdraw and deposit, but we validate everything before making any changes to ensure atomicity.
Time Complexity: O(1) for all operations (constructor, transfer, deposit, withdraw) as they involve only constant-time array access and arithmetic operations.
Space Complexity: O(n) where n is the number of accounts, used to store the balance array. Each individual operation uses O(1) additional space.
class Bank:
def __init__(self, balance: List[int]):
"""
Initialize the bank with the given account balances.
Store balances in a list where index i represents account i+1.
"""
self.balances = balance
self.n = len(balance)
def _is_valid_account(self, account: int) -> bool:
"""
Helper method to check if an account number is valid.
Accounts are 1-indexed, so valid range is [1, n].
"""
return 1 <= account <= self.n
def transfer(self, account1: int, account2: int, money: int) -> bool:
"""
Transfer money from account1 to account2.
Returns true if successful, false otherwise.
"""
# Validate both accounts exist
if not self._is_valid_account(account1) or not self._is_valid_account(account2):
return False
# Check if source account has sufficient funds
# Convert to 0-indexed for array access
if self.balances[account1 - 1] < money:
return False
# Perform the transfer
self.balances[account1 - 1] -= money
self.balances[account2 - 1] += money
return True
def deposit(self, account: int, money: int) -> bool:
"""
Deposit money into the specified account.
Returns true if successful, false otherwise.
"""
# Validate account exists
if not self._is_valid_account(account):
return False
# Perform the deposit (convert to 0-indexed)
self.balances[account - 1] += money
return True
def withdraw(self, account: int, money: int) -> bool:
"""
Withdraw money from the specified account.
Returns true if successful, false otherwise.
"""
# Validate account exists
if not self._is_valid_account(account):
return False
# Check sufficient funds (convert to 0-indexed)
if self.balances[account - 1] < money:
return False
# Perform the withdrawal
self.balances[account - 1] -= money
return True