Problem Statement in English
You have been tasked with implementing a simple bank system that supports three operations: transfer, deposit, and withdraw.
The bank system should maintain account balances and ensure that all operations are valid.
Bank accounts are numbered from 1 to n, where n is the total number of accounts. Each account has an initial balance.
Approach
We can use a hashmap to store the account balances.
Each operation (transfer, deposit, withdraw) can be performed in constant time by checking and updating the balances in the hashmap.
Solution in Python
class Bank:
def __init__(self, balance: List[int]):
self.hm = {}
self.n = len(balance)
for i in range(len(balance)):
self.hm[i + 1] = balance[i]
def transfer(self, account1: int, account2: int, money: int) -> bool:
if 1 <= account1 <= self.n and 1 <= account2 <= self.n and self.hm[account1] >= money:
self.hm[account1] -= money
self.hm[account2] += money
return True
return False
def deposit(self, account: int, money: int) -> bool:
if 1 <= account <= self.n:
self.hm[account] += money
return True
return False
def withdraw(self, account: int, money: int) -> bool:
if 1 <= account <= self.n and self.hm[account] >= money:
self.hm[account] -= money
return True
return False
Complexity
Time: $O(1)$ for all operations except the initialization, which is $O(n)$
Space: $O(n)$
Since we use a hashmap
And we are done.