Simple Bank System - Problem
You're building the core system for a modern digital bank that needs to handle millions of transactions daily. The bank manages n accounts numbered from 1 to n, where each account has an initial balance stored in a 0-indexed array.
Your mission: Implement a robust Bank class that can safely execute three types of financial operations:
- ๐ธ Transfer: Move money between two accounts
- ๐ฐ Deposit: Add money to an account
- ๐ง Withdraw: Remove money from an account
Security Rules: A transaction is valid only if:
- All account numbers are between
1andn - The account has sufficient balance for withdrawals/transfers
Your system should return true for successful transactions and false for invalid ones, ensuring no money is lost or created!
Input & Output
example_1.py โ Basic Operations
$
Input:
Bank([10, 100, 20, 50, 30])
operations: deposit(5, 20), withdraw(3, 10), transfer(1, 2, 5)
โบ
Output:
deposit: true, withdraw: true, transfer: true
๐ก Note:
All operations are valid: account 5 gets $20 (30โ50), account 3 loses $10 (20โ10), and $5 moves from account 1 to 2 (10โ5, 100โ105)
example_2.py โ Invalid Operations
$
Input:
Bank([10, 100, 20, 50, 30])
operations: withdraw(6, 10), transfer(1, 6, 5), withdraw(1, 50)
โบ
Output:
withdraw: false, transfer: false, withdraw: false
๐ก Note:
Account 6 doesn't exist (invalid), transfer to invalid account fails, and account 1 has insufficient balance ($10 < $50)
example_3.py โ Edge Cases
$
Input:
Bank([100])
operations: withdraw(1, 100), deposit(1, 50), transfer(1, 1, 25)
โบ
Output:
withdraw: true, deposit: true, transfer: true
๐ก Note:
Single account bank: withdraw entire balance (100โ0), deposit $50 (0โ50), self-transfer $25 (no net change but valid)
Constraints
- n == balance.length
- 1 โค n โค 105
- 0 โค balance[i] โค 1012
- 1 โค account, account1, account2 โค n
- 0 โค money โค 1012
- At most 104 calls will be made to each function
Visualization
Tap to expand
Understanding the Visualization
1
Account Validation
First, check if the account number exists (between 1 and n) - like verifying a valid account number
2
Balance Verification
For withdrawals/transfers, ensure sufficient funds - like checking account balance before dispensing cash
3
Atomic Transaction
Update account balances simultaneously - like a secure database transaction that either completes fully or fails completely
Key Takeaway
๐ฏ Key Insight: The banking system achieves optimal performance through direct array indexing (O(1) access) combined with proper validation, making it suitable for high-frequency transaction processing.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code