Multi-Stage Banking Ledger: Cash, Statements, Fees, and Delayed Transfers
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Implement an in-memory multi-stage ledger service (BankService) along with exact currency/timestamp helpers and text report formatters across five progressive milestones:
-
Cash operations & account balances (
ATM):parse_money(text: str) -> intconverts ASCII dollar strings ("$14.25","14.25","14") into integer cents (1425,1425,1400) without floating-point rounding, raisingValueErroron negative numbers, commas, non-ASCII digits, or anything other than zero or two decimal places.format_money(cents: int) -> strrenders cents with a dollar sign and two decimals (1425 -> "$14.25",5 -> "$0.05").parse_time(text: str) -> datetimeandformat_time(t: datetime) -> strparse and format"YYYY-MM-DD H:MM:SS"where hours< 10are not zero-padded ("2025-03-15 3:00:00").deposit_cash(time, account, amount)andwithdraw_cash(time, account, amount)openaccountat0cents on first contact. Withdrawals exceeding the usable balance decline (return False) and leave the balance unchanged; valid deposits and covered withdrawals succeed (return True).get_current_balance(account, time=None)returns usable cents (0ifaccountwas never opened), advancing the service clock first whentimeis passed.balance_report(service)returns["account amount", "<ACCT> $<D.CC>", ...]ordered alphabetically by account ID.
-
Per-account transaction statements (
Transaction):- Every executed or declined banking action appends a
Transaction(time, account, credit, debit, status, kind, balance, counterparty)capturing the account's usable balance right after the event (statusis"SUCCESS"or"FAILED"). Transaction.columns()returns[time_str, account, credit_str, debit_str, status, kind, balance_str], using""for whichever ofcreditordebitis0.statement(account)returns that account's rows in chronological order (keeping processing order on timestamp ties).statement_report(service, header=CREDIT_DEBIT_HEADER)outputsheaderfollowed by all accounts' rows (sorted by account ID), joining each row's non-empty column strings with single spaces.
- Every executed or declined banking action appends a
-
Atomic internal transfers (
INSTANT TRANSFER):instant_transfer(time, source, destination, amount)requiressourceto be an already-open account (ValueErrorotherwise). Ifdestination == source,destinationis not open, orsourcelacksamountcents, record one"FAILED"debit row onsourceand returnFalsewithout modifying any balance. Otherwise atomically debitsourceand creditdestination(settingcounterpartyon each row) and returnTrue.
-
External bank transfers with configurable fees (
FEE):BankService(fee_rule=one_cent_fee)accepts a callablefee_rule(amount) -> intreturning a non-negative integer cent fee (ValueErrorif negative orbool;one_cent_feereturns1cent).external_transfer_out(time, account, external_account, amount)requiresaccountto be open and checksbalance >= amount + fee. If insufficient, it records a single"FAILED"debit row ("INSTANT TRANSFER", debitamount) with no fee row and returnsFalse; otherwise it debitsamount("INSTANT TRANSFER") and—whenfee > 0—debitsfeeas its own"FEE"row.external_transfer_in(time, external_account, account, amount)requiresaccountto be open and checksbalance + amount >= fee(else one"FAILED"credit row ofamount); on success it creditsamount("INSTANT TRANSFER") and—whenfee > 0—debitsfee("FEE").
-
Delayed transfers & clock settlement (
SLOW TRANSFER):advance_to(time)raisesValueErroriftimeprecedes the service's current timestamp; otherwise it settles all pending slow transfers witharrival_time <= timein earliest-arrival order (ties broken in initiation order), stamping each receiver's"SLOW TRANSFER"credit row witharrival_time.slow_transfer(time, source, destination, amount, arrival_time)requiresarrival_time > time(ValueErrorotherwise) and an opensource. Ifdestination == source,destinationis unknown, orsourcelacksamount, record one"FAILED""SLOW TRANSFER"debit row onsourceand returnFalse. Otherwise debitsourceimmediately and holdamountin transit (reported viafunds_in_transit()) until the clock reachesarrival_time.run_actions(service, lines)ignores blank lines, parses comma-separated commands (DEPOSIT,WITHDRAW,BALANCE,TRANSFER,EXTERNAL_OUT,EXTERNAL_IN,SLOW_TRANSFER), stably sorts them by timestamp only, and applies them sequentially.
Examples
Example 1
Input lines passed to run_actions(svc, lines):
2025-03-15 4:00:00,WITHDRAW,ACCT101,$6.00
2025-03-15 2:00:00,DEPOSIT,ACCT202,$15.00
2025-03-15 1:00:00,DEPOSIT,ACCT101,$14.00
2025-03-15 3:00:00,WITHDRAW,ACCT202,$20.00
balance_report(svc):
account amount
ACCT101 $8.00
ACCT202 $15.00
statement_report(svc, CREDIT_DEBIT_HEADER):
time account credit debit status type balance
2025-03-15 1:00:00 ACCT101 $14.00 SUCCESS ATM $14.00
2025-03-15 4:00:00 ACCT101 $6.00 SUCCESS ATM $8.00
2025-03-15 2:00:00 ACCT202 $15.00 SUCCESS ATM $15.00
2025-03-15 3:00:00 ACCT202 $20.00 FAILED ATM $15.00
Walk-through: run_actions sorts the shuffled commands chronologically. ACCT101 deposits $14.00 at 1:00:00 and withdraws $6.00 at 4:00:00 ($8.00 left). ACCT202 deposits $15.00 at 2:00:00, then attempts a $20.00 withdrawal at 3:00:00, which is logged as FAILED with balance unchanged at $15.00.
Example 2
Input lines passed to run_actions(svc, lines) (default $0.01 external fee):
2025-03-15 1:00:00,DEPOSIT,ACCT101,$12.00
2025-03-15 1:00:00,DEPOSIT,ACCT202,$5.00
2025-03-15 7:00:00,BALANCE,ACCT202
2025-03-15 3:00:00,SLOW_TRANSFER,ACCT101,ACCT202,$4.00,2025-03-15 6:00:00
2025-03-15 4:00:00,EXTERNAL_OUT,ACCT202,EXT900,$2.00
2025-03-15 2:00:00,TRANSFER,ACCT101,ACCT202,$3.00
statement_report(svc, AMOUNT_HEADER):
time account amount status type balance
2025-03-15 1:00:00 ACCT101 $12.00 SUCCESS ATM $12.00
2025-03-15 2:00:00 ACCT101 $3.00 SUCCESS INSTANT TRANSFER $9.00
2025-03-15 3:00:00 ACCT101 $4.00 SUCCESS SLOW TRANSFER $5.00
2025-03-15 1:00:00 ACCT202 $5.00 SUCCESS ATM $5.00
2025-03-15 2:00:00 ACCT202 $3.00 SUCCESS INSTANT TRANSFER $8.00
2025-03-15 4:00:00 ACCT202 $2.00 SUCCESS INSTANT TRANSFER $6.00
2025-03-15 4:00:00 ACCT202 $0.01 SUCCESS FEE $5.99
2025-03-15 6:00:00 ACCT202 $4.00 SUCCESS SLOW TRANSFER $9.99
Walk-through: At 2:00:00, $3.00 moves instantly (ACCT101 -> $9.00, ACCT202 -> $8.00). At 3:00:00, ACCT101 initiates a $4.00 slow transfer arriving at 6:00:00, reducing ACCT101 to $5.00 right away. At 4:00:00, ACCT202 sends $2.00 externally ($2.00 debit plus $0.01 FEE row -> $5.99). Finally, the 7:00:00 BALANCE query advances the clock past 6:00:00, delivering the $4.00 slow transfer stamped at 6:00:00 ($9.99).
Constraints
- All monetary amounts inside
BankServiceare positiveintcent counts (amount <= 0orboolraisesValueErrorwithout advancing the clock or recording a statement row). - Direct calls into
BankServicemust supply non-decreasingdatetimevalues (ValueErrorotherwise). - Balances must never become negative, and floating-point arithmetic must never be used for currency values.
Step-by-step walkthrough
Turn open questions into crisp invariants
In a multi-milestone coding session, new rules unlock every 15 to 20 minutes. Mutating balances directly inside
deposit_cashandwithdraw_cashduring Milestone 1 forces painful rewrites once statements, fees, and delayed settlements arrive. Locking down crisp invariants up front keeps every new milestone additive:Design decision Rule in this implementation Timestamp ordering BankServiceenforces non-decreasing timestamps (ValueErroron regression).run_actionssorts command lines by timestamp using a stable sort (a sort that keeps tied items in their original file sequence).Account creation The first ATM call ( deposit_cashorwithdraw_cash) opens an account at$0.00before executing. Transfers require an already-open origin (ValueErrorotherwise). Unopened accounts report$0.00.Overdrafts Balances never go negative. Any debit exceeding usable funds records one FAILEDrow and leaves the balance intact.Non-positive or non-int amounts Caller bug: raise ValueErrorbefore advancing the clock or recording any row.FAILEDrows represent valid banking requests that were declined, not malformed API calls.Self-transfer or unknown target Declined request: append one FAILEDrow on the sender's statement and returnFalse.External transfer fee Computed via an injected fee_rule(amount) -> fee_centscallable (default flat$0.01). Billed to our customer's account as a separateFEErow; outgoing checksbalance >= amount + fee.Delayed (slow) transfers Debit the sender right away at time; credit the receiver only once the clock reachesarrival_time(arrival_time > time). While in flight, funds belong to neither usable balance.Architecture split: FileInterface / run_actions --> parses CSV lines, stably sorts by timestamp, formats text tables | v BankService --> operates strictly on integer cents and datetime objectsRepresent currency as integer cents and format hours portably
Never store currency in
float. Computers use binary floating-point (base-2 fractions), which cannot represent most decimal hundredths exactly: in Python,0.10 + 0.20evaluates to0.30000000000000004. Across dozens of operations, tiny drift can flip abalance >= amountcomparison by a cent. Representing every monetary value as an integer cent count ($14.25->1425) keeps addition, subtraction, and comparisons 100% exact.String parsing must bypass
floattoo. Split directly on".":"$14.25"splits into"14"dollars and"25"cents, giving14 * 100 + 25 = 1425cents. Checkcleaned.isascii()alongsideisdigit(), because Python'sstr.isdigit()accepts non-ASCII Unicode digits like'٣', which should be rejected.For timestamps, output lines render single-digit hours unpadded (
2025-03-15 3:00:00). Standard%Hpads with a leading zero (03), whereas%-Hrelies on Unix C libraries and raisesValueErroron Windows. Interpolating{t.hour}works identically everywhere.from datetime import datetime TIME_FORMAT = "%Y-%m-%d %H:%M:%S" def parse_money(text: str) -> int: """'$12.34', '12.34' or '12' -> 1234 cents. Never goes through float.""" cleaned = text.strip() if cleaned.startswith("$"): cleaned = cleaned[1:] if "." in cleaned: dollars_str, cents_str = cleaned.split(".", 1) else: dollars_str, cents_str = cleaned, "00" # Reject non-ASCII digits (str.isdigit() accepts Unicode digits like '٣') # and require at least one dollar digit plus exactly two cent digits. is_valid_ascii = cleaned.isascii() has_valid_parts = dollars_str.isdigit() and cents_str.isdigit() and len(cents_str) == 2 if not is_valid_ascii or not has_valid_parts: raise ValueError(f"bad amount: {text!r}") return int(dollars_str) * 100 + int(cents_str) def format_money(cents: int) -> str: """1299 -> '$12.99', 5 -> '$0.05'.""" sign = "" if cents < 0: sign = "-" cents = -cents dollars = cents // 100 rem_cents = cents % 100 return f"{sign}${dollars}.{rem_cents:02d}" def parse_time(text: str) -> datetime: """'2025-03-15 3:00:00' -> datetime. strptime %H accepts 1-digit or 2-digit hours.""" return datetime.strptime(text.strip(), TIME_FORMAT) def format_time(t: datetime) -> str: """datetime -> '2025-03-15 3:00:00' (hour not zero-padded).""" # Build hour with t.hour because strftime('%-H') fails on Windows C runtimes. return f"{t:%Y-%m-%d} {t.hour}:{t:%M:%S}"Snapshot statement rows at execution time
Every field of a statement entry—including the post-transaction usable balance—is known at the instant an operation runs. Recording a complete
Transactionobject right then avoids replaying history later, which grows brittle once declined attempts, fees, and delayed arrivals interleave.One
Transactionlayout cleanly serves both report formats: - Separatecreditanddebitintegers (0when unused) map directly to the 7-columnCREDIT_DEBIT_HEADER(credit debit). - For the 6-columnAMOUNT_HEADER, every row populates eithercreditordebit(never both), so rendering the zero side as""and joining non-empty strings with" "produces both report styles from the samecolumns()method!from dataclasses import dataclass from datetime import datetime from typing import List SUCCESS = "SUCCESS" FAILED = "FAILED" ATM = "ATM" INSTANT = "INSTANT TRANSFER" FEE = "FEE" SLOW = "SLOW TRANSFER" @dataclass class Transaction: """One statement row captured at the exact moment an action is processed.""" time: datetime account: str credit: int # cents added to this account (0 if none) debit: int # cents taken from this account (0 if none) status: str # SUCCESS or FAILED kind: str # ATM, INSTANT TRANSFER, FEE, SLOW TRANSFER balance: int # this account's usable balance right after the row counterparty: str = "" def columns(self) -> List[str]: """[time, account, credit, debit, status, type, balance]; '' for unused side.""" credit_text = format_money(self.credit) if self.credit else "" debit_text = format_money(self.debit) if self.debit else "" return [ format_time(self.time), self.account, credit_text, debit_text, self.status, self.kind, format_money(self.balance), ]Milestones 1 and 2: shared ledger primitives and ATM cash
Across all five milestones, an account's ledger changes through only three internal helpers: 1.
_credit: add cents tobalances[account]and append aSUCCESSrow. 2._debit: subtract cents frombalances[account]and append aSUCCESSrow. 3._fail: keepbalances[account]unchanged and append aFAILEDrow.Funneling every operation through those three primitives enforces an ironclad invariant (a condition guaranteed to hold after every step):
balances[account]always matches thebalancerecorded on the latest row ofhistory[account].Because timestamps never move backward, appending to
history[account]keeps each account's statement ordered chronologically, preserving call order on same-second ties. Notice_check_amountexplicitly rejectsbool(isinstance(True, int)isTruein Python!) beforeadvance_to(time)runs, so invalid calls never move the service clock.from datetime import datetime from typing import Callable, Dict, List, Optional, Tuple def one_cent_fee(amount: int) -> int: """Default fee for an external transfer: a flat $0.01 (1 cent).""" return 1 class BankService: """In-memory bank. Amounts are integer cents; times arrive in non-decreasing order.""" def __init__(self, fee_rule: Callable[[int], int] = one_cent_fee) -> None: self.fee_rule = fee_rule # balances: maps open account_id -> usable integer cents, e.g. {"ACCT101": 800} self.balances: Dict[str, int] = {} # history: maps open account_id -> chronological list of Transaction rows self.history: Dict[str, List[Transaction]] = {} # in_transit: min-heap of (arrival_time, transfer_id, source, destination, amount) self.in_transit: List[Tuple[datetime, int, str, str, int]] = [] self.next_transfer_id = 0 self.now: Optional[datetime] = None def _check_amount(self, amount: int) -> None: # Reject bool explicitly because isinstance(True, int) is True in Python. if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0: raise ValueError("amount must be a positive integer number of cents") def _open(self, account: str) -> None: if account not in self.balances: self.balances[account] = 0 self.history[account] = [] def _record(self, time: datetime, account: str, credit: int, debit: int, status: str, kind: str, counterparty: str) -> None: row = Transaction( time=time, account=account, credit=credit, debit=debit, status=status, kind=kind, balance=self.balances[account], counterparty=counterparty, ) self.history[account].append(row) def _credit(self, time: datetime, account: str, amount: int, kind: str, counterparty: str = "") -> None: self.balances[account] += amount self._record(time, account, amount, 0, SUCCESS, kind, counterparty) def _debit(self, time: datetime, account: str, amount: int, kind: str, counterparty: str = "") -> None: self.balances[account] -= amount self._record(time, account, 0, amount, SUCCESS, kind, counterparty) def _fail(self, time: datetime, account: str, credit: int, debit: int, kind: str, counterparty: str = "") -> bool: self._record(time, account, credit, debit, FAILED, kind, counterparty) return False def get_current_balance(self, account: str, time: Optional[datetime] = None) -> int: if time is not None: self.advance_to(time) return self.balances.get(account, 0) def deposit_cash(self, time: datetime, account: str, amount: int) -> bool: self._check_amount(amount) self.advance_to(time) self._open(account) self._credit(time, account, amount, ATM) return True def withdraw_cash(self, time: datetime, account: str, amount: int) -> bool: self._check_amount(amount) self.advance_to(time) self._open(account) # Strictly less (<): withdrawing the exact full balance is allowed and leaves $0.00. if self.balances[account] < amount: return self._fail(time, account, 0, amount, ATM) self._debit(time, account, amount, ATM) return TrueMilestone 3: atomic instant transfers
An internal transfer touches two accounts in one operation. Keeping it atomic (all-or-nothing, so either both sides update or neither changes) means checking every precondition before mutating anything:
- Validate
amount > 0and confirmsourceis open before callingadvance_to(time)so invalid source accounts raiseValueErrorwithout advancing the clock. - Check
_can_move(source, destination, amount): requiredestination != source,destinationopen, andbalances[source] >= amount. - On failure, log one
FAILEDdebit row onsourceand returnFalse. - Otherwise call
_debitonsourcefollowed immediately by_creditondestination.
ACCT101 ($12.00) -- instant_transfer($3.00) --> ACCT202 ($5.00) 1. Preconditions: source open? yes. dest != source & open? yes. 1200 >= 300? yes. 2. _debit(ACCT101, 300) -> balance becomes 900, appends SUCCESS debit row ($3.00 -> $9.00) 3. _credit(ACCT202, 300) -> balance becomes 800, appends SUCCESS credit row ($3.00 -> $8.00)class BankService: def _require_open(self, account: str) -> None: if account not in self.balances: raise ValueError(f"unknown account: {account}") def _can_move(self, source: str, destination: str, amount: int) -> bool: # Self-transfers and unknown destinations decline cleanly rather than raising. if destination == source or destination not in self.balances: return False return self.balances[source] >= amount def instant_transfer(self, time: datetime, source: str, destination: str, amount: int) -> bool: # Validate inputs before advance_to so an invalid call never advances the clock. self._check_amount(amount) self._require_open(source) self.advance_to(time) # Check destination and funds before mutating either account (atomic move). if not self._can_move(source, destination, amount): return self._fail(time, source, 0, amount, INSTANT, destination) self._debit(time, source, amount, INSTANT, destination) self._credit(time, destination, amount, INSTANT, source) return True- Validate
Milestone 4: external transfers with pluggable fee pricing
Accounts at another institution have no balance in our service—only their identifier is saved in
counterparty. Fee handling introduces two key rules:- Pluggable pricing: Injecting
fee_rule: Callable[[int], int]intoBankService.__init__isolates fee schedules from ledger logic. Flat$0.01isreturn 1;0.25%rounded half-up in pure integer math is(amount * 25 + 5000) // 10000. - Outgoing funds check (
amount + fee): If an account holds$2.00and attempts a$2.00external transfer with a$0.01fee, checking onlybalance >= amountwould let the principal pass and push the balance to-$0.01on the fee! Checkingbalances[account] < amount + feedeclines the transfer cleanly with zero fee row. - Incoming funds check (
balance + amount >= fee): Arriving funds can cover the fee, so verifybalances[account] + amount >= fee, creditamount, and then debitfeeas a separateFEErow.
class BankService: def _check_fee(self, fee: int) -> None: if isinstance(fee, bool) or not isinstance(fee, int) or fee < 0: raise ValueError("fee must be a non-negative integer number of cents") def _charge_fee(self, time: datetime, account: str, fee: int) -> None: if fee > 0: self._debit(time, account, fee, FEE) def external_transfer_out(self, time: datetime, account: str, external_account: str, amount: int) -> bool: """Send money from `account` to another bank. The account pays amount + fee.""" self._check_amount(amount) self._require_open(account) fee = self.fee_rule(amount) self._check_fee(fee) self.advance_to(time) # Sender must afford both the principal and the fee; otherwise nothing moves. if self.balances[account] < amount + fee: return self._fail(time, account, 0, amount, INSTANT, external_account) self._debit(time, account, amount, INSTANT, external_account) self._charge_fee(time, account, fee) return True def external_transfer_in(self, time: datetime, external_account: str, account: str, amount: int) -> bool: """Receive money from another bank, then deduct the fee from the same account.""" self._check_amount(amount) self._require_open(account) fee = self.fee_rule(amount) self._check_fee(fee) self.advance_to(time) # Incoming funds can help cover the fee, so check balance + amount < fee. if self.balances[account] + amount < fee: return self._fail(time, account, amount, 0, INSTANT, external_account) self._credit(time, account, amount, INSTANT, external_account) self._charge_fee(time, account, fee) return True- Pluggable pricing: Injecting
Milestone 5: delayed transfers and min-heap settlement
Between initiation (
time) and delivery (arrival_time), delayed-transfer funds cannot be spent by either account. We hold unsettled transfers inself.in_transit, structured as a min-heap (a binary tree stored in an array where index0always holds the minimum element, enablingO(log P)insertion andO(log P)pop-earliest):Initiation at 3:00 ($4.00 from ACCT101 to ACCT202, arriving 6:00): 1. Debit ACCT101 right away at 3:00 ($9.00 -> $5.00, SLOW TRANSFER row). 2. Push (6:00, id=1, "ACCT101", "ACCT202", 400) onto self.in_transit. At 4:00 (while still in transit): ACCT101 usable = $5.00 | in_transit = $4.00 | ACCT202 usable = $5.99 (after $2.00 + $0.01 external out) Later action at 7:00 (BALANCE ACCT202): advance_to(7:00) pops every heap entry with arrival_time <= 7:00: 3. Pop (6:00, id=1, ...) -> Credit ACCT202 stamped at 6:00 ($5.99 -> $9.99).Three details keep
advance_tosubtle-bug-free: 1. Inclusive<=check:in_transit[0][0] <= timeensures funds arriving at6:00settle before a6:00withdrawal checks the receiver's usable balance. 2. Arrival timestamp: Stamp the receiver's credit row witharrival(6:00), not the later triggertime(7:00). Because every valid call runsadvance_tofirst andarrival_time > initiation_time, settled credits always append in chronological order. 3. Monotonic tie-breakertransfer_id: Placingself.next_transfer_idsecond in the tuple settles simultaneous arrivals in initiation order and avoids comparing account strings.import heapq class BankService: def advance_to(self, time: datetime) -> None: """Move the clock to `time`, delivering every slow transfer with arrival <= time.""" if self.now is not None and time < self.now: raise ValueError("actions must be given in non-decreasing time order") # Use <= so funds arriving at 8:00 are settled before an 8:00 withdrawal runs. while self.in_transit and self.in_transit[0][0] <= time: arrival, _, source, destination, amount = heapq.heappop(self.in_transit) # Stamp the receiver's credit row with arrival, not the later trigger time. self._credit(arrival, destination, amount, SLOW, source) self.now = time def slow_transfer(self, time: datetime, source: str, destination: str, amount: int, arrival_time: datetime) -> bool: """Debit sender now; credit destination only when clock reaches arrival_time.""" self._check_amount(amount) if arrival_time <= time: raise ValueError("arrival_time must be strictly later than time") self._require_open(source) self.advance_to(time) if not self._can_move(source, destination, amount): return self._fail(time, source, 0, amount, SLOW, destination) # Remove funds from sender immediately so they cannot be spent twice while in flight. self._debit(time, source, amount, SLOW, destination) self.next_transfer_id += 1 heap_entry = (arrival_time, self.next_transfer_id, source, destination, amount) heapq.heappush(self.in_transit, heap_entry) return True def funds_in_transit(self) -> int: total = 0 for transfer in self.in_transit: total += transfer[4] return totalReporting, CSV command runner, and complete solution
Finally, wire up the reporting and batch-runner helpers outside
BankService: -statement_reportwalksservice.accounts()(sorted alphabetically) and joins each row's non-empty column strings with" ". -run_actionsparses non-blank CSV lines and sorts withkey=_action_timeonly so Python's stable Timsort preserves original file order whenever timestamps tie.from typing import Callable, Dict, Iterable, List, Optional, Tuple from dataclasses import dataclass from datetime import datetime import heapq SUCCESS = "SUCCESS" FAILED = "FAILED" ATM = "ATM" INSTANT = "INSTANT TRANSFER" FEE = "FEE" SLOW = "SLOW TRANSFER" TIME_FORMAT = "%Y-%m-%d %H:%M:%S" CREDIT_DEBIT_HEADER = "time account credit debit status type balance" # Part 2 AMOUNT_HEADER = "time account amount status type balance" # Parts 3-5 # ---------- Phase 1: Exact money and timestamp helpers ---------- def parse_money(text: str) -> int: """'$12.34', '12.34' or '12' -> 1234 cents. Never goes through float.""" cleaned = text.strip() if cleaned.startswith("$"): cleaned = cleaned[1:] if "." in cleaned: dollars_str, cents_str = cleaned.split(".", 1) else: dollars_str, cents_str = cleaned, "00" # Reject non-ASCII digits (str.isdigit() accepts Unicode digits like '٣') # and require at least one dollar digit plus exactly two cent digits. is_valid_ascii = cleaned.isascii() has_valid_parts = dollars_str.isdigit() and cents_str.isdigit() and len(cents_str) == 2 if not is_valid_ascii or not has_valid_parts: raise ValueError(f"bad amount: {text!r}") return int(dollars_str) * 100 + int(cents_str) def format_money(cents: int) -> str: """1299 -> '$12.99', 5 -> '$0.05'.""" sign = "" if cents < 0: sign = "-" cents = -cents dollars = cents // 100 rem_cents = cents % 100 return f"{sign}${dollars}.{rem_cents:02d}" def parse_time(text: str) -> datetime: """'2025-03-15 3:00:00' -> datetime. strptime %H accepts 1-digit or 2-digit hours.""" return datetime.strptime(text.strip(), TIME_FORMAT) def format_time(t: datetime) -> str: """datetime -> '2025-03-15 3:00:00' (hour not zero-padded).""" # Build hour with t.hour because strftime('%-H') fails on Windows C runtimes. return f"{t:%Y-%m-%d} {t.hour}:{t:%M:%S}" # ---------- Phase 2: Immutable-style statement row ---------- @dataclass class Transaction: """One statement row captured at the exact moment an action is processed.""" time: datetime account: str credit: int # cents added to this account (0 if none) debit: int # cents taken from this account (0 if none) status: str # SUCCESS or FAILED kind: str # ATM, INSTANT TRANSFER, FEE, SLOW TRANSFER balance: int # this account's usable balance right after the row counterparty: str = "" def columns(self) -> List[str]: """[time, account, credit, debit, status, type, balance]; '' for unused side.""" credit_text = format_money(self.credit) if self.credit else "" debit_text = format_money(self.debit) if self.debit else "" return [ format_time(self.time), self.account, credit_text, debit_text, self.status, self.kind, format_money(self.balance), ] def one_cent_fee(amount: int) -> int: """Default fee for an external transfer: a flat $0.01 (1 cent).""" return 1 # ---------- Phase 3: Core in-memory banking service ---------- class BankService: """In-memory bank. Amounts are integer cents; times arrive in non-decreasing order.""" def __init__(self, fee_rule: Callable[[int], int] = one_cent_fee) -> None: self.fee_rule = fee_rule # balances: maps open account_id -> usable integer cents, e.g. {"ACCT101": 800} self.balances: Dict[str, int] = {} # history: maps open account_id -> chronological list of Transaction rows self.history: Dict[str, List[Transaction]] = {} # in_transit: min-heap of (arrival_time, transfer_id, source, destination, amount) # Ordered by earliest arrival_time; transfer_id breaks ties in initiation order. self.in_transit: List[Tuple[datetime, int, str, str, int]] = [] self.next_transfer_id = 0 self.now: Optional[datetime] = None # --- Internal validation and ledger primitives --- def _check_amount(self, amount: int) -> None: # Reject bool explicitly because isinstance(True, int) is True in Python. if isinstance(amount, bool) or not isinstance(amount, int) or amount <= 0: raise ValueError("amount must be a positive integer number of cents") def _check_fee(self, fee: int) -> None: if isinstance(fee, bool) or not isinstance(fee, int) or fee < 0: raise ValueError("fee must be a non-negative integer number of cents") def _open(self, account: str) -> None: if account not in self.balances: self.balances[account] = 0 self.history[account] = [] def _require_open(self, account: str) -> None: if account not in self.balances: raise ValueError(f"unknown account: {account}") def _record(self, time: datetime, account: str, credit: int, debit: int, status: str, kind: str, counterparty: str) -> None: row = Transaction( time=time, account=account, credit=credit, debit=debit, status=status, kind=kind, balance=self.balances[account], counterparty=counterparty, ) self.history[account].append(row) def _credit(self, time: datetime, account: str, amount: int, kind: str, counterparty: str = "") -> None: # Update balance and append statement row together so they never drift apart. self.balances[account] += amount self._record(time, account, amount, 0, SUCCESS, kind, counterparty) def _debit(self, time: datetime, account: str, amount: int, kind: str, counterparty: str = "") -> None: # Caller has already verified that balances[account] >= amount. self.balances[account] -= amount self._record(time, account, 0, amount, SUCCESS, kind, counterparty) def _fail(self, time: datetime, account: str, credit: int, debit: int, kind: str, counterparty: str = "") -> bool: # Failed attempts leave balances[account] untouched but still record a row. self._record(time, account, credit, debit, FAILED, kind, counterparty) return False def _can_move(self, source: str, destination: str, amount: int) -> bool: # Self-transfers and unknown destinations decline cleanly rather than raising. if destination == source or destination not in self.balances: return False return self.balances[source] >= amount # --- Part 5 settlement clock (called at the start of every valid action) --- def advance_to(self, time: datetime) -> None: """Move the clock to `time`, delivering every slow transfer with arrival <= time.""" if self.now is not None and time < self.now: raise ValueError("actions must be given in non-decreasing time order") # Use <= so funds arriving at 8:00 are settled before an 8:00 withdrawal runs. while self.in_transit and self.in_transit[0][0] <= time: arrival, _, source, destination, amount = heapq.heappop(self.in_transit) # Stamp the receiver's credit row with arrival, not the later trigger time. self._credit(arrival, destination, amount, SLOW, source) self.now = time # --- Parts 1 and 2: ATM balance, deposits, and withdrawals --- def get_current_balance(self, account: str, time: Optional[datetime] = None) -> int: """Usable balance in cents; 0 for an account never seen.""" if time is not None: self.advance_to(time) return self.balances.get(account, 0) def deposit_cash(self, time: datetime, account: str, amount: int) -> bool: self._check_amount(amount) self.advance_to(time) self._open(account) self._credit(time, account, amount, ATM) return True def withdraw_cash(self, time: datetime, account: str, amount: int) -> bool: self._check_amount(amount) self.advance_to(time) self._open(account) # Strictly less (<): withdrawing the exact full balance is allowed and leaves $0.00. if self.balances[account] < amount: return self._fail(time, account, 0, amount, ATM) self._debit(time, account, amount, ATM) return True # --- Part 3: All-or-nothing instant transfer --- def instant_transfer(self, time: datetime, source: str, destination: str, amount: int) -> bool: # Validate inputs before advance_to so an invalid call never advances the clock. self._check_amount(amount) self._require_open(source) self.advance_to(time) # Check destination and funds before mutating either account (atomic move). if not self._can_move(source, destination, amount): return self._fail(time, source, 0, amount, INSTANT, destination) self._debit(time, source, amount, INSTANT, destination) self._credit(time, destination, amount, INSTANT, source) return True # --- Part 4: External transfers with a pluggable fee --- def _charge_fee(self, time: datetime, account: str, fee: int) -> None: if fee > 0: self._debit(time, account, fee, FEE) def external_transfer_out(self, time: datetime, account: str, external_account: str, amount: int) -> bool: """Send money from `account` to another bank. The account pays amount + fee.""" self._check_amount(amount) self._require_open(account) fee = self.fee_rule(amount) self._check_fee(fee) self.advance_to(time) # Sender must afford both the principal and the fee; otherwise nothing moves. if self.balances[account] < amount + fee: return self._fail(time, account, 0, amount, INSTANT, external_account) self._debit(time, account, amount, INSTANT, external_account) self._charge_fee(time, account, fee) return True def external_transfer_in(self, time: datetime, external_account: str, account: str, amount: int) -> bool: """Receive money from another bank, then deduct the fee from the same account.""" self._check_amount(amount) self._require_open(account) fee = self.fee_rule(amount) self._check_fee(fee) self.advance_to(time) # Incoming funds can help cover the fee, so check balance + amount < fee. if self.balances[account] + amount < fee: return self._fail(time, account, amount, 0, INSTANT, external_account) self._credit(time, account, amount, INSTANT, external_account) self._charge_fee(time, account, fee) return True # --- Part 5: Slow transfers held in transit until arrival_time --- def slow_transfer(self, time: datetime, source: str, destination: str, amount: int, arrival_time: datetime) -> bool: """Debit sender now; credit destination only when clock reaches arrival_time.""" self._check_amount(amount) if arrival_time <= time: raise ValueError("arrival_time must be strictly later than time") self._require_open(source) self.advance_to(time) if not self._can_move(source, destination, amount): return self._fail(time, source, 0, amount, SLOW, destination) # Remove funds from sender immediately so they cannot be spent twice while in flight. self._debit(time, source, amount, SLOW, destination) self.next_transfer_id += 1 heap_entry = (arrival_time, self.next_transfer_id, source, destination, amount) heapq.heappush(self.in_transit, heap_entry) return True def funds_in_transit(self) -> int: total = 0 for transfer in self.in_transit: total += transfer[4] return total # --- Ledger inspection --- def accounts(self) -> List[str]: return sorted(self.balances) def statement(self, account: str) -> List[Transaction]: """Rows of one account in chronological order (ties in processing order).""" return list(self.history.get(account, [])) # ---------- Phase 4: Formatting reports and parsing action files ---------- def _join_non_empty(columns: List[str]) -> str: # Dropping the empty credit or debit string collapses two columns into one space-separated row. non_empty = [] for column in columns: if column: non_empty.append(column) return " ".join(non_empty) def balance_report(service: BankService) -> List[str]: """Part 1 output: header followed by 'ACCOUNT $X.XX' sorted by account id.""" lines = ["account amount"] for account in service.accounts(): balance_str = format_money(service.get_current_balance(account)) lines.append(f"{account} {balance_str}") return lines def statement_report(service: BankService, header: str = CREDIT_DEBIT_HEADER) -> List[str]: """Part 2+ output: rows grouped by sorted account id, then in chronological order.""" lines = [header] for account in service.accounts(): for row in service.statement(account): lines.append(_join_non_empty(row.columns())) return lines def parse_action(line: str) -> Tuple[datetime, str, List[str]]: """'2025-03-15 1:00:00,DEPOSIT,ACCT101,$14.00' -> (time, 'DEPOSIT', ['ACCT101', '$14.00']).""" parts = [] for part in line.split(","): parts.append(part.strip()) if len(parts) < 3: raise ValueError(f"malformed action line: {line!r}") return parse_time(parts[0]), parts[1].upper(), parts[2:] def _require_arg_count(kind: str, args: List[str], expected: int) -> None: if len(args) != expected: raise ValueError(f"{kind} expects {expected} arguments, got {len(args)}") def apply_action(service: BankService, time: datetime, kind: str, args: List[str]) -> None: if kind == "DEPOSIT": _require_arg_count(kind, args, 2) service.deposit_cash(time, args[0], parse_money(args[1])) elif kind == "WITHDRAW": _require_arg_count(kind, args, 2) service.withdraw_cash(time, args[0], parse_money(args[1])) elif kind == "BALANCE": _require_arg_count(kind, args, 1) service.get_current_balance(args[0], time) elif kind == "TRANSFER": _require_arg_count(kind, args, 3) service.instant_transfer(time, args[0], args[1], parse_money(args[2])) elif kind == "EXTERNAL_OUT": _require_arg_count(kind, args, 3) service.external_transfer_out(time, args[0], args[1], parse_money(args[2])) elif kind == "EXTERNAL_IN": _require_arg_count(kind, args, 3) service.external_transfer_in(time, args[0], args[1], parse_money(args[2])) elif kind == "SLOW_TRANSFER": _require_arg_count(kind, args, 4) service.slow_transfer(time, args[0], args[1], parse_money(args[2]), parse_time(args[3])) else: raise ValueError(f"unknown action: {kind}") def _action_time(action: Tuple[datetime, str, List[str]]) -> datetime: return action[0] def run_actions(service: BankService, lines: Iterable[str]) -> None: """Parse non-blank lines, stably sort by timestamp only, and execute in order.""" actions = [] for line in lines: if line.strip(): actions.append(parse_action(line)) # Sort only by timestamp so Python's stable sort preserves file order on ties. actions.sort(key=_action_time) for time, kind, args in actions: apply_action(service, time, kind, args) class FileInterface: """Thin I/O wrapper that keeps file paths out of BankService.""" def __init__(self, service: BankService) -> None: self.service = service def perform_bank_actions(self, input_path: str) -> None: with open(input_path, encoding="utf-8") as f: run_actions(self.service, f) def write_bank_statements(self, output_path: str, header: str = AMOUNT_HEADER) -> None: with open(output_path, "w", encoding="utf-8") as f: for line in statement_report(self.service, header): f.write(line + "\n")✅ Submit now — all tests should pass.
Intuition & how it works
Picture BankService as a methodical teller operating with three tools on the counter:
1. A cash drawer per open customer (balances), storing exact integer cents so pennies never suffer floating-point drift.
2. An append-only ledger per customer (history), where every approved credit, approved debit, or declined request writes one permanent ink entry containing the exact balance right after that event.
3. An escrow tray (in_transit) for delayed transfers, ordered with earliest-arriving envelopes on top—a min-heap (a priority queue that keeps the smallest timestamp at index 0 for O(1) peek and O(log P) pop).
Naive designs tend to break down as new milestones unlock: storing amounts in float (where 0.10 + 0.20 produces 0.30000000000000004), trying to reconstruct historical balances when formatting statements (which falls apart once declined rows, fees, and delayed arrivals mix), and duplicating balance-update code inside every new method. Funneling all money updates through three tiny primitives—_credit, _debit, and _fail—and advancing the settlement clock (advance_to) at the start of every valid call keeps all five stages consistent.
Here is how Example 2 flows across ACCT101 and ACCT202 in integer cents:
1:00 DEPOSIT ACCT101 $12.00, DEPOSIT ACCT202 $5.00
-> balances: {ACCT101: 1200, ACCT202: 500}, in_transit: []
2:00 TRANSFER ACCT101 -> ACCT202 $3.00
-> balances: {ACCT101: 900, ACCT202: 800}
3:00 SLOW_TRANSFER ACCT101 -> ACCT202 $4.00 (arrives 6:00)
-> _debit(ACCT101, 400) right away; push (6:00, id=1, ACCT101->ACCT202, 400) to min-heap
-> balances: {ACCT101: 500, ACCT202: 800}, in_transit: [(6:00, 400)]
4:00 EXTERNAL_OUT ACCT202 -> EXT900 $2.00 (flat $0.01 fee)
-> advance_to(4:00): 6:00 > 4:00, nothing settles yet
-> check 800 >= 200 + 1 (ok!): _debit(ACCT202, 200) -> $6.00, then _debit(ACCT202, 1, FEE) -> $5.99
7:00 BALANCE ACCT202
-> advance_to(7:00): pops 6:00 transfer, calls _credit(6:00, ACCT202, 400) -> $9.99
-> returns 999 cents ($9.99), stamped in ACCT202's statement at 6:00
Complexity
Let N be the number of input commands, R the total number of recorded statement rows, A the count of opened accounts, and P the peak count of delayed transfers simultaneously in flight.
- ATM operations, instant transfers, and external transfers:
O(1)amortized time per call (excluding any due settlements popped inadvance_to). Each call performs a constant number of dictionary lookups (balances,history) and appends one or twoTransactionentries to a Python list, where amortized time means rare array resizes average out to constant cost per append. - Delayed transfers:
O(log P)time per initiation andO(log P)per settlement. Pushing ontoin_transitand popping due items inadvance_toeach traverse the height of a binary min-heap of size at mostP, totalingO(S log P)acrossSdelayed transfers. - Reporting (
statement_report):O(A log A + R)time. SortingAaccount IDs takesO(A log A)comparisons, and formatting every recorded row visits each of theRentries once. - Batch runner (
run_actions):O(N log N + R)time. ParsingNlines is linear, ordering them with Python's stable sort (preserving input order on equal keys) takesO(N log N), and executing all commands costsO(N + S log P). - Space:
O(A + R + P). One integer balance and list header per open account (A), oneTransactioninstance per statement row (R <= 2 * N), and one heap tuple per unsettled slow transfer (P).
Edge cases
- Withdrawing the exact full balance:
$8.00withdrawn from$8.00succeeds and leaves$0.00because the guard checksbalance < amountrather than<=. Requesting$8.01logsFAILEDand leaves$8.00. - Outgoing external transfer covering principal but not the fee: Sending
$5.00with a$0.01fee from a$5.00balance declines as a singleFAILEDtransfer row with noFEErow and leaves$5.00untouched. - Tied timestamps and exact arrival boundaries: Two withdrawals at
3:00run in file order so the second sees the updated balance. Becauseadvance_tochecksarrival_time <= time, a delayed transfer arriving at6:00settles before a6:00withdrawal runs. - Out-of-order arrival times: A delayed transfer initiated at
10:00arriving at11:00settles ahead of one initiated at9:00arriving at12:00, because the min-heap orders byarrival_time. - Invalid API calls never advance the clock: Calls raising
ValueError(amount <= 0, passing booleanTrue, unopened transfer origin,arrival_time <= time, or backward timestamps) fail beforeadvance_toexecutes, leavingself.nowandin_transitunchanged. - Unsettled transfers at end of batch: Transfers whose
arrival_timeexceeds the last processed timestamp stay inin_transit(counted byfunds_in_transit()), with only the sender's debit row recorded so far.
Common mistakes
- Using
floatfor dollars and cents: Binary floating-point rounding introduces penny errors in balances and>=checks; parse strings directly into integer cents (ordecimal.Decimal). - Debiting the sender before validating the destination: Mutating
sourcebefore checking whetherdestinationis open or distinct fromsourcecorrupts balances when validation fails. - Checking
balance >= amountinstead ofbalance >= amount + fee: Omitting the fee from the outgoing check lets the fee deduction drive the balance below zero. - Stamping slow-transfer arrival rows with the trigger timestamp: When a transfer arrives at
6:00and the next command runs at7:00, the receiver's credit row must carry6:00(arrival), not7:00(time). - Sorting full
(time, kind, args)tuples inrun_actions: Tuple comparison breaks equal-timestamp ties alphabetically bykind(DEPOSITahead ofWITHDRAW), reordering same-second commands; sort withkey=_action_timeonly. - Using
strftime("%-H")for unpadded hours:%-Hcrashes withValueErroron Windows C runtimes; format{t.hour}directly.
Alternative approaches
decimal.Decimalwith explicit quantization: Helpful when interest accrual or FX conversions produce sub-cent fractions; quantize ledger postings withDecimal("0.01")and an explicit rounding mode such asROUND_HALF_UP.- Double-entry ledger: Model
"ATM_VAULT","EXTERNAL_CLEARING","FEE_REVENUE", and"ESCROW_IN_TRANSIT"as internal accounts so every transaction is a balanced zero-sum pair of postings, making global reconciliation a simple sum-to-zero check.
Follow-up questions
-
Suppose two worker threads execute simultaneous transfers in opposite directions between the same pair of accounts—how do you prevent race conditions and deadlocks? A deadlock occurs when Thread 1 locks account A and waits for account B while Thread 2 locks B and waits for A, blocking both forever. Give every account its own mutex, reject
source == destinationup front, and always acquire the two account locks in canonical sorted order—first, second = sorted([source, destination])—before checking balances and updating both accounts. Because every thread requestsAbeforeB, a cycle in the wait graph is impossible. In a relational database, wrap both updates inside one transaction, runSELECT ... FOR UPDATEon the two account rows ordered byaccount_id, and guardbalance >= amountin theWHEREclause. -
If the process terminates mid-batch and the command log is re-run from the top, how do you guarantee no operation is applied twice? Attach a deterministic idempotency key (a unique request ID, or
(batch_id, line_number)) to every command, where idempotent means processing the same command repeatedly produces the exact same state as processing it once. Store each processed key in the same atomic database transaction that updates the account balance and appends statement rows—including commands that recordedFAILED, so re-running does not append duplicateFAILEDrows. Upon restart, skip any command whose key is already committed. -
How would you extend the ledger to let users cancel an unsettled delayed transfer or handle a post-settlement rejection from an external bank? Return a
transfer_idfromslow_transferand maintain a status table (PENDING,DELIVERED,CANCELLED). Cancelling whilePENDINGflips the status toCANCELLED, appends a compensating credit row to restore the sender's usable balance, and uses lazy deletion (leaving the old entry inside the min-heap and ignoring it whenadvance_toeventually pops it, avoiding anO(P)heap search). If an external bank rejects a transfer after settlement, keep historical rows immutable and append a new reversal credit entry stamped at the rejection time, following explicit product rules on whether the transfer fee is refunded. -
Once an account accumulates millions of ledger entries, how can you query its historical balance at an arbitrary timestamp quickly? Because every
Transactionsnapshotsbalanceright after execution and each account'shistorylist is already sorted bytime, binary search (repeatedly halving the search interval viabisect_rightto locate the last entry withrow.time <= query_time) answers point-in-time balance queries inO(log R)time—roughly 20 comparisons for a million entries! In SQL storage, a composite B-tree index on(account_id, time DESC, seq_id DESC)servesWHERE account_id = ? AND time <= ? ORDER BY time DESC, seq_id DESC LIMIT 1in a single index probe.
Follow-up questions
- Suppose two worker threads execute simultaneous transfers in opposite directions between the same pair of accounts—how do you prevent race conditions and deadlocks?
- If the process terminates mid-batch and the command log is re-run from the top, how do you guarantee no operation is applied twice?
- How would you extend the ledger to let users cancel an unsettled delayed transfer or handle a post-settlement rejection from an external bank?
- Once an account accumulates millions of ledger entries, how can you query its historical balance at an arbitrary timestamp quickly?
Similar questions
- Backdated Loan Ledger with Fee-Priority Repayments
- Two-Bucket Billing Ledger with Retroactive Events
- Loan Servicing Backend for Repayments and Investor Distributions
- Schema-Less In-Memory Record Store
- Deterministic Financial Services for Out-of-Order Loan Events
- In-Memory Record Store with Composable Filter Queries
More Valon interview questions
- Backdated Loan Ledger with Fee-Priority Repayments Medium
- Deterministic Financial Services for Out-of-Order Loan Events Medium
- Schema-Less In-Memory Record Store Medium Pro
- Loan Servicing Backend for Repayments and Investor Distributions Medium Pro
- In-Memory Record Store with Composable Filter Queries Hard Pro
- In-Memory Relational Table Engine Hard Pro
- Two-Bucket Billing Ledger with Retroactive Events Medium Pro