Design a BankAccount class in Python with deposit, withdraw and balance, rejecting overdrafts and bad amounts with ValueError. OOP basics, tested live.
The problem
Implement BankAccount:
deposit(amount)— adds money; raisesValueErrorifamount <= 0withdraw(amount)— removes money; raisesValueErrorifamount <= 0or greater than the balancebalance()— returns the current balance
A new account starts at 0, or at an optional opening balance.
Examples
Example 1
Input
run_ops(BankAccount, [], [["deposit", 1000], ["withdraw", 300], ["balance"]])
Expected output
[None, None, 700]
Example 2
Input
raises(BankAccount(100).withdraw, 500)
Expected output
'ValueError'
+ 4 hidden tests on Submit — opening balance, failed withdrawal changes nothing.
Edge cases to ask about
- Overdraft
- Zero/negative amounts
- Opening balance
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| State + validated methods | O(1) | O(1) | Every method guards its invariant: balance never negative. |
Walkthrough of the optimal approach (try it yourself first)
Keep the balance on the instance and make every method protect the invariant — the balance can never go negative. Validate before mutating, so a rejected withdrawal leaves the account unchanged.
For real money, use decimal.Decimal (or integer cents) rather than floats.
Complexity: O(1) time, O(1) space. Each method does constant work on one number.
Reveal the reference solution
class BankAccount: def __init__(self, opening=0): self._balance = opening def deposit(self, amount): if amount <= 0: raise ValueError("deposit must be positive") self._balance += amount def withdraw(self, amount): if amount <= 0: raise ValueError("withdrawal must be positive") if amount > self._balance: raise ValueError("insufficient funds") self._balance -= amount def balance(self): return self._balance
Follow-ups interviewers ask
- Why not store money as float?
- Add a transaction history.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of BankAccount Class With Deposit and Withdraw in Python?
The optimal solution runs in O(1) time and O(1) auxiliary space. Each method does constant work on one number.
What follow-up questions do interviewers ask about BankAccount Class With Deposit and Withdraw?
Why not store money as float? Add a transaction history.
