Build a Bank, Validate Passwords, and Evaluate Expressions
Data Structure DesignModel answerLast updated
Design a mini banking system, write a password strength checker with generator, and parse arithmetic expressions with full operator precedence.
Three-Part Coding Challenge
You have 90 minutes to complete three independent problems. For each one, state your assumptions out loud, handle invalid input gracefully, and aim for clean, testable code. The interviewer is as interested in how you reason through edge cases as in whether the final output is correct.
Part 1: Mini Banking System
Build a class that manages accounts and supports four operations. Decide on and declare your contracts before writing any code.
Operations to support:
create_account(timestamp, account_id)— registers a new account with a zero balance; returnsFalseif the ID is already taken.deposit(timestamp, account_id, amount)— adds funds and returns the new balance; returnsNonefor an unknown account or a non-positive amount.transfer(timestamp, source_id, dest_id, amount)— moves funds between two accounts and returns the new source balance; returnsNoneif either account is missing, if source and destination are the same, if the amount is non-positive, or if the source has insufficient funds.top_spenders(timestamp, n)— returns up tonaccount IDs formatted as"id(total_spent)", ordered by total outgoing money descending, with ties broken alphabetically by ID.
Edge cases to consider: duplicate account creation, self-transfers, exact-balance transfers, n exceeding the number of accounts, and ties in the ranking.
Part 2: Password Strength Checker and Generator
Validator: given a string, return a list of all violated rules (not just a pass/fail boolean). A password passes if it:
- is between 8 and 64 characters long,
- contains at least one lowercase letter, one uppercase letter, one digit, and one character from a defined set of special characters,
- contains no whitespace,
- has no character appearing three or more times consecutively.
Generator: produce a random password of a given length (default 16) that satisfies all rules. Use a cryptographically secure source of randomness.
Edge cases to consider: empty strings, exactly 8 or 64 characters, a triple-repeat buried inside an otherwise valid password, and Unicode input.
Part 3: Arithmetic Expression Evaluator
Write a function that takes a string representing an arithmetic expression and returns its integer result.
Requirements:
- Support
+,-,*,/and parentheses. - Handle unary
+and-(e.g."-(2+3)","--4"). - Ignore whitespace.
- Integer division truncates toward zero (so
7 / -2 = -3, not-4). - Raise a clear error on division by zero, unbalanced parentheses, or invalid tokens.
Edge cases to consider: chained unary operators, left-associativity for subtraction and division, and trailing or unconsumed tokens.
Hints
Hint 1
For the banking system, a failed transfer must leave both balances completely unchanged — check all preconditions before touching any state. Track outgoing totals in a separate dict so ranking doesn't require scanning transactions.
Hint 2
For password validation, check every rule independently and collect all failures before returning — a bare True/False is less useful. For generation, seed the result with one character from each required class before filling the rest, then shuffle; use `secrets`, not `random`.
Hint 3
For expression evaluation, a recursive-descent parser maps cleanly onto operator precedence: one function per grammar level (expr → term → factor). Truncation toward zero is `int(a / b)` in Python, not `a // b`, which floors toward negative infinity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Three independent problems, each with a different core skill: simulation with careful state management, rule checking with secure randomness, and grammar-driven parsing. The notes below cover design decisions, correctness arguments, complexity, and common mistakes.
Part 1: Mini Banking System
Design
Two hash maps cover everything: balance[id] and outgoing[id]. Every mutation checks all preconditions atomically — either all changes happen or none do. This is the key property interviewers probe on transfer.
from typing import Optional
class Bank:
def __init__(self) -> None:
self.balance: dict[str, int] = {}
self.outgoing: dict[str, int] = {}
def create_account(self, ts: int, account_id: str) -> bool:
if account_id in self.balance:
return False
self.balance[account_id] = 0
self.outgoing[account_id] = 0
return True
def deposit(self, ts: int, account_id: str, amount: int) -> Optional[int]:
if account_id not in self.balance or amount <= 0:
return None
self.balance[account_id] += amount
return self.balance[account_id]
def transfer(self, ts: int, src: str, dst: str, amount: int) -> Optional[int]:
if (src == dst
or src not in self.balance
or dst not in self.balance
or amount <= 0
or self.balance[src] < amount):
return None
self.balance[src] -= amount
self.balance[dst] += amount
self.outgoing[src] += amount
return self.balance[src]
def top_spenders(self, ts: int, n: int) -> list[str]:
ranked = sorted(self.outgoing.items(), key=lambda kv: (-kv[1], kv[0]))
return [f"{acc}({total})" for acc, total in ranked[:n]]
Complexity
create_account,deposit,transfer: O(1).top_spenders: O(A log A); useheapq.nsmallestto get O(A log n) if A is large.- Space: O(A) for A accounts.
Common mistakes
- Updating
balancebefore checking all conditions ontransfer, so a failed call leaves partial state. - Forgetting
src == dstas a rejection condition. - Using
<instead of<=for the insufficient-funds check, which incorrectly rejects exact-balance transfers.
Part 2: Password Validator and Generator
Design
Return a list of violations rather than a boolean — every rule is checked independently so callers get the full picture. For generation, guarantee each character class appears by seeding the result before filling the remainder, then shuffle.
secrets is the right module. random uses a Mersenne Twister that is seeded from system time and is not cryptographically secure. Interviewers in security-aware companies notice the difference.
import secrets
import string
SPECIALS = "!@#$%^&*()-_=+[]{};:,.?/"
def validate_password(pw: str) -> list[str]:
errors = []
if not 8 <= len(pw) <= 64:
errors.append("length must be 8–64")
if not any(c.islower() for c in pw):
errors.append("missing lowercase letter")
if not any(c.isupper() for c in pw):
errors.append("missing uppercase letter")
if not any(c.isdigit() for c in pw):
errors.append("missing digit")
if not any(c in SPECIALS for c in pw):
errors.append("missing special character")
if any(c.isspace() for c in pw):
errors.append("contains whitespace")
if any(pw[i] == pw[i+1] == pw[i+2] for i in range(len(pw) - 2)):
errors.append("three or more consecutive identical characters")
return errors
def generate_password(length: int = 16) -> str:
if not 8 <= length <= 64:
raise ValueError("length must be 8–64")
pools = [
string.ascii_lowercase,
string.ascii_uppercase,
string.digits,
SPECIALS,
]
alphabet = "".join(pools)
rng = secrets.SystemRandom()
while True:
chars = [secrets.choice(p) for p in pools]
chars += [secrets.choice(alphabet) for _ in range(length - len(pools))]
rng.shuffle(chars)
pw = "".join(chars)
if not validate_password(pw):
return pw
Complexity
- Validation: O(L), O(1) extra space.
- Generation: expected O(L); the
while Trueloop almost never retries because the triple-repeat rule is rarely triggered at these lengths.
Common mistake
Using random.shuffle or random.choice instead of secrets. Also: forgetting to re-validate the generated password — the shuffle can accidentally create a triple run.
Part 3: Arithmetic Expression Evaluator
Design
A recursive-descent parser maps each precedence level to one function, which is cleaner under time pressure than a two-stack shunting-yard approach and easier to extend later.
Grammar:
expr := term (('+' | '-') term)*
term := factor (('*' | '/') factor)*
factor := ('+' | '-') factor | NUMBER | '(' expr ')'
Precedence falls naturally from the nesting. Left-associativity comes from the loops, so 8 - 3 - 2 correctly evaluates to 3.
def evaluate(expression: str) -> int:
tokens = tokenize(expression)
pos = [0] # mutable index shared across recursive calls
def peek() -> Optional[str]:
return tokens[pos[0]] if pos[0] < len(tokens) else None
def consume(expected: Optional[str] = None) -> str:
tok = tokens[pos[0]]
if expected and tok != expected:
raise ValueError(f"expected {expected!r}, got {tok!r}")
pos[0] += 1
return tok
def parse_expr() -> int:
result = parse_term()
while peek() in ('+', '-'):
op = consume()
right = parse_term()
result = result + right if op == '+' else result - right
return result
def parse_term() -> int:
result = parse_factor()
while peek() in ('*', '/'):
op = consume()
right = parse_factor()
if op == '/':
if right == 0:
raise ZeroDivisionError("division by zero")
result = int(result / right) # truncate toward zero
else:
result *= right
return result
def parse_factor() -> int:
tok = peek()
if tok == '-':
consume()
return -parse_factor()
if tok == '+':
consume()
return parse_factor()
if tok == '(':
consume('(')
val = parse_expr()
consume(')')
return val
if tok is not None and tok.lstrip('-').isdigit():
return int(consume())
raise ValueError(f"unexpected token: {tok!r}")
result = parse_expr()
if pos[0] != len(tokens):
raise ValueError(f"unconsumed tokens starting at {tokens[pos[0]]!r}")
return result
def tokenize(s: str) -> list[str]:
import re
tokens = re.findall(r'\d+|[+\-*/()]', s.replace(' ', ''))
if ''.join(tokens) != s.replace(' ', ''):
raise ValueError("invalid characters in expression")
return tokens
Complexity
- O(n) time — each token is visited exactly once.
- O(n) space for the token list plus call stack depth proportional to parenthesis nesting.
Common mistakes
- Using Python's
//operator for integer division:7 // -2is-4(floor), but the spec requires-3(truncate toward zero). Useint(a / b)instead. - Not checking that all tokens were consumed, so
"1 2"silently returns1. - Forgetting to thread a mutable position through recursive calls, leading to incorrect index state.