Bank System with Withdraw, Deposit, and Undo Operations
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-12-15
Problem Statement
Design a Bank Account Management System that supports basic financial transactions (deposit, withdraw) with the ability to undo the last operation. The system should ensure correctness, thread-safety, and extensibility for future banking operations.
Functional Requirements (FR)
1.Account Management
•Each account has a unique ID, owner, and balance.
•Support multiple accounts.
2.Deposit Operation
•Add money to the account balance.
•Record the transaction in history.
3.Withdraw Operation
•Deduct money if sufficient funds are available.
•Prevent overdrafts (unless overdraft facility is supported).
•Record the transaction in history.
4.Undo Operation
•Revert the last successful transaction (deposit or withdraw).
•Undo should restore the account balance to the previous state.
•Support multiple undo steps (like a stack).
5.Transaction History
•Maintain chronological record of all operations.
•Each transaction includes type, amount, timestamp, and resulting balance.
Non-Functional Requirements (NFR)
•Thread Safety – Handle concurrent deposits/withdrawals safely.
•Atomicity – A transaction is either fully applied or not at all.
•Scalability – Support many accounts and transactions.
•Extensibility – Easy to add new operations (e.g., transfer, interest calculation).
Core Entities & Attributes
•Bank → accounts[], getAccount(accountId)
•Account → accountId, ownerName, balance, transactionHistory
•Transaction → transactionId, type (DEPOSIT/WITHDRAW), amount, timestamp, prevBalance, newBalance
•TransactionManager → applyTransaction(account, transaction), undoLastTransaction(account)
Key Operations / APIs
•createAccount(ownerName, initialBalance)
•deposit(accountId, amount)
•withdraw(accountId, amount)
•undoLastTransaction(accountId)
•getBalance(accountId)
•getTransactionHistory(accountId)
Design Considerations
Undo Implementation
•Use a stack per account to store previous transactions.
•undo() pops the last transaction and reverts balance accordingly.
Concurrency
•Synchronize on account objects to avoid race conditions in deposits/withdrawals.
Design Patterns
•Command Pattern → Each transaction is a command (execute, undo).
•Memento Pattern → Store previous state for undo functionality.
•Strategy Pattern → For different transaction types.
Error Handling
•Insufficient balance for withdraw.
•No transaction available to undo.
Example
Input sequence:
•Deposit(1000)
•Withdraw(200)
•Undo()
Result:
•Final Balance = 1000 (since withdraw was undone).
✅ This LLD problem tests:
•OOP modeling of Accounts, Transactions, and Undo mechanism.
•Command/Memento design patterns.
•Handling concurrency & correctness in financial systems