Problem Description
Implement a simple bank system which supports deposit, withdraw, and transfer operations on accounts. The bank has n accounts (1-indexed), each with an initial balance provided by a 0-indexed array. Each operation must validate that the account number is valid and that sufficient funds exist for withdraw or transfer operations.
Key Insights
- Maintain an array (or list) to store account balances.
- Remember to convert between 1-indexed account numbers (used in operations) and 0-indexed data structure.
- Validate each transaction by checking:
- The account numbers (and both in transfers) are within valid range.
- The account to withdraw or transfer from has enough balance to cover the money amount.
- Each operation (deposit, withdraw, transfer) can then be processed in constant O(1) time.
Space and Time Complexity
Time Complexity: O(1) per operation as each operation requires a constant number of checks and arithmetic operations.
Space Complexity: O(n), where n is the number of bank accounts stored in the balance array.
Solution
The solution involves creating a Bank class that maintains the current balance in an array. Each method (deposit, withdraw, and transfer) first checks whether the provided account number(s) are valid (by ensuring the account numbers are between 1 and n). For withdraw and transfer operations, additionally check that the source account has a sufficient balance to handle the deduction. The operations are executed with simple arithmetic adjustments on the array values. This method guarantees constant-time operations and uses minimal extra space.