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:

  1. Cash operations & account balances (ATM):

    • parse_money(text: str) -> int converts ASCII dollar strings ("$14.25", "14.25", "14") into integer cents (1425, 1425, 1400) without floating-point rounding, raising ValueError on negative numbers, commas, non-ASCII digits, or anything other than zero or two decimal places.
    • format_money(cents: int) -> str renders cents with a dollar sign and two decimals (1425 -> "$14.25", 5 -> "$0.05").
    • parse_time(text: str) -> datetime and format_time(t: datetime) -> str parse and format "YYYY-MM-DD H:MM:SS" where hours < 10 are not zero-padded ("2025-03-15 3:00:00").
    • deposit_cash(time, account, amount) and withdraw_cash(time, account, amount) open account at 0 cents 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 (0 if account was never opened), advancing the service clock first when time is passed. balance_report(service) returns ["account amount", "<ACCT> $<D.CC>", ...] ordered alphabetically by account ID.
  2. 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 (status is "SUCCESS" or "FAILED").
    • Transaction.columns() returns [time_str, account, credit_str, debit_str, status, kind, balance_str], using "" for whichever of credit or debit is 0.
    • statement(account) returns that account's rows in chronological order (keeping processing order on timestamp ties). statement_report(service, header=CREDIT_DEBIT_HEADER) outputs header followed by all accounts' rows (sorted by account ID), joining each row's non-empty column strings with single spaces.
  3. Atomic internal transfers (INSTANT TRANSFER):

    • instant_transfer(time, source, destination, amount) requires source to be an already-open account (ValueError otherwise). If destination == source, destination is not open, or source lacks amount cents, record one "FAILED" debit row on source and return False without modifying any balance. Otherwise atomically debit source and credit destination (setting counterparty on each row) and return True.
  4. External bank transfers with configurable fees (FEE):

    • BankService(fee_rule=one_cent_fee) accepts a callable fee_rule(amount) -> int returning a non-negative integer cent fee (ValueError if negative or bool; one_cent_fee returns 1 cent).
    • external_transfer_out(time, account, external_account, amount) requires account to be open and checks balance >= amount + fee. If insufficient, it records a single "FAILED" debit row ("INSTANT TRANSFER", debit amount) with no fee row and returns False; otherwise it debits amount ("INSTANT TRANSFER") and—when fee > 0—debits fee as its own "FEE" row.
    • external_transfer_in(time, external_account, account, amount) requires account to be open and checks balance + amount >= fee (else one "FAILED" credit row of amount); on success it credits amount ("INSTANT TRANSFER") and—when fee > 0—debits fee ("FEE").
  5. Delayed transfers & clock settlement (SLOW TRANSFER):

    • advance_to(time) raises ValueError if time precedes the service's current timestamp; otherwise it settles all pending slow transfers with arrival_time <= time in earliest-arrival order (ties broken in initiation order), stamping each receiver's "SLOW TRANSFER" credit row with arrival_time.
    • slow_transfer(time, source, destination, amount, arrival_time) requires arrival_time > time (ValueError otherwise) and an open source. If destination == source, destination is unknown, or source lacks amount, record one "FAILED" "SLOW TRANSFER" debit row on source and return False. Otherwise debit source immediately and hold amount in transit (reported via funds_in_transit()) until the clock reaches arrival_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 BankService are positive int cent counts (amount <= 0 or bool raises ValueError without advancing the clock or recording a statement row).
  • Direct calls into BankService must supply non-decreasing datetime values (ValueError otherwise).
  • Balances must never become negative, and floating-point arithmetic must never be used for currency values.

Step-by-step walkthrough

  1. 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_cash and withdraw_cash during 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 BankService enforces non-decreasing timestamps (ValueError on regression). run_actions sorts 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_cash or withdraw_cash) opens an account at $0.00 before executing. Transfers require an already-open origin (ValueError otherwise). Unopened accounts report $0.00.
    Overdrafts Balances never go negative. Any debit exceeding usable funds records one FAILED row and leaves the balance intact.
    Non-positive or non-int amounts Caller bug: raise ValueError before advancing the clock or recording any row. FAILED rows represent valid banking requests that were declined, not malformed API calls.
    Self-transfer or unknown target Declined request: append one FAILED row on the sender's statement and return False.
    External transfer fee Computed via an injected fee_rule(amount) -> fee_cents callable (default flat $0.01). Billed to our customer's account as a separate FEE row; outgoing checks balance >= amount + fee.
    Delayed (slow) transfers Debit the sender right away at time; credit the receiver only once the clock reaches arrival_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 objects
    
  2. Represent 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.20 evaluates to 0.30000000000000004. Across dozens of operations, tiny drift can flip a balance >= amount comparison 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 float too. Split directly on ".": "$14.25" splits into "14" dollars and "25" cents, giving 14 * 100 + 25 = 1425 cents. Check cleaned.isascii() alongside isdigit(), because Python's str.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 %H pads with a leading zero (03), whereas %-H relies on Unix C libraries and raises ValueError on 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}"
    
  3. 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 Transaction object right then avoids replaying history later, which grows brittle once declined attempts, fees, and delayed arrivals interleave.

    One Transaction layout cleanly serves both report formats: - Separate credit and debit integers (0 when unused) map directly to the 7-column CREDIT_DEBIT_HEADER (credit debit). - For the 6-column AMOUNT_HEADER, every row populates either credit or debit (never both), so rendering the zero side as "" and joining non-empty strings with " " produces both report styles from the same columns() 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),
            ]
    
  4. 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 to balances[account] and append a SUCCESS row. 2. _debit: subtract cents from balances[account] and append a SUCCESS row. 3. _fail: keep balances[account] unchanged and append a FAILED row.

    Funneling every operation through those three primitives enforces an ironclad invariant (a condition guaranteed to hold after every step): balances[account] always matches the balance recorded on the latest row of history[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_amount explicitly rejects bool (isinstance(True, int) is True in Python!) before advance_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 True
    
  5. Milestone 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:

    1. Validate amount > 0 and confirm source is open before calling advance_to(time) so invalid source accounts raise ValueError without advancing the clock.
    2. Check _can_move(source, destination, amount): require destination != source, destination open, and balances[source] >= amount.
    3. On failure, log one FAILED debit row on source and return False.
    4. Otherwise call _debit on source followed immediately by _credit on destination.
    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
    
  6. 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] into BankService.__init__ isolates fee schedules from ledger logic. Flat $0.01 is return 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.00 and attempts a $2.00 external transfer with a $0.01 fee, checking only balance >= amount would let the principal pass and push the balance to -$0.01 on the fee! Checking balances[account] < amount + fee declines the transfer cleanly with zero fee row.
    • Incoming funds check (balance + amount >= fee): Arriving funds can cover the fee, so verify balances[account] + amount >= fee, credit amount, and then debit fee as a separate FEE row.
    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
    
  7. 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 in self.in_transit, structured as a min-heap (a binary tree stored in an array where index 0 always holds the minimum element, enabling O(log P) insertion and O(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_to subtle-bug-free: 1. Inclusive <= check: in_transit[0][0] <= time ensures funds arriving at 6:00 settle before a 6:00 withdrawal checks the receiver's usable balance. 2. Arrival timestamp: Stamp the receiver's credit row with arrival (6:00), not the later trigger time (7:00). Because every valid call runs advance_to first and arrival_time > initiation_time, settled credits always append in chronological order. 3. Monotonic tie-breaker transfer_id: Placing self.next_transfer_id second 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 total
    
  8. Reporting, CSV command runner, and complete solution

    Finally, wire up the reporting and batch-runner helpers outside BankService: - statement_report walks service.accounts() (sorted alphabetically) and joins each row's non-empty column strings with " ". - run_actions parses non-blank CSV lines and sorts with key=_action_time only 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 in advance_to). Each call performs a constant number of dictionary lookups (balances, history) and appends one or two Transaction entries 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 and O(log P) per settlement. Pushing onto in_transit and popping due items in advance_to each traverse the height of a binary min-heap of size at most P, totaling O(S log P) across S delayed transfers.
  • Reporting (statement_report): O(A log A + R) time. Sorting A account IDs takes O(A log A) comparisons, and formatting every recorded row visits each of the R entries once.
  • Batch runner (run_actions): O(N log N + R) time. Parsing N lines is linear, ordering them with Python's stable sort (preserving input order on equal keys) takes O(N log N), and executing all commands costs O(N + S log P).
  • Space: O(A + R + P). One integer balance and list header per open account (A), one Transaction instance per statement row (R <= 2 * N), and one heap tuple per unsettled slow transfer (P).

Edge cases

  • Withdrawing the exact full balance: $8.00 withdrawn from $8.00 succeeds and leaves $0.00 because the guard checks balance < amount rather than <=. Requesting $8.01 logs FAILED and leaves $8.00.
  • Outgoing external transfer covering principal but not the fee: Sending $5.00 with a $0.01 fee from a $5.00 balance declines as a single FAILED transfer row with no FEE row and leaves $5.00 untouched.
  • Tied timestamps and exact arrival boundaries: Two withdrawals at 3:00 run in file order so the second sees the updated balance. Because advance_to checks arrival_time <= time, a delayed transfer arriving at 6:00 settles before a 6:00 withdrawal runs.
  • Out-of-order arrival times: A delayed transfer initiated at 10:00 arriving at 11:00 settles ahead of one initiated at 9:00 arriving at 12:00, because the min-heap orders by arrival_time.
  • Invalid API calls never advance the clock: Calls raising ValueError (amount <= 0, passing boolean True, unopened transfer origin, arrival_time <= time, or backward timestamps) fail before advance_to executes, leaving self.now and in_transit unchanged.
  • Unsettled transfers at end of batch: Transfers whose arrival_time exceeds the last processed timestamp stay in in_transit (counted by funds_in_transit()), with only the sender's debit row recorded so far.

Common mistakes

  • Using float for dollars and cents: Binary floating-point rounding introduces penny errors in balances and >= checks; parse strings directly into integer cents (or decimal.Decimal).
  • Debiting the sender before validating the destination: Mutating source before checking whether destination is open or distinct from source corrupts balances when validation fails.
  • Checking balance >= amount instead of balance >= 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:00 and the next command runs at 7:00, the receiver's credit row must carry 6:00 (arrival), not 7:00 (time).
  • Sorting full (time, kind, args) tuples in run_actions: Tuple comparison breaks equal-timestamp ties alphabetically by kind (DEPOSIT ahead of WITHDRAW), reordering same-second commands; sort with key=_action_time only.
  • Using strftime("%-H") for unpadded hours: %-H crashes with ValueError on Windows C runtimes; format {t.hour} directly.

Alternative approaches

  • decimal.Decimal with explicit quantization: Helpful when interest accrual or FX conversions produce sub-cent fractions; quantize ledger postings with Decimal("0.01") and an explicit rounding mode such as ROUND_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 == destination up 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 requests A before B, a cycle in the wait graph is impossible. In a relational database, wrap both updates inside one transaction, run SELECT ... FOR UPDATE on the two account rows ordered by account_id, and guard balance >= amount in the WHERE clause.

  • 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 recorded FAILED, so re-running does not append duplicate FAILED rows. 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_id from slow_transfer and maintain a status table (PENDING, DELIVERED, CANCELLED). Cancelling while PENDING flips the status to CANCELLED, 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 when advance_to eventually pops it, avoiding an O(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 Transaction snapshots balance right after execution and each account's history list is already sorted by time, binary search (repeatedly halving the search interval via bisect_right to locate the last entry with row.time <= query_time) answers point-in-time balance queries in O(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) serves WHERE account_id = ? AND time <= ? ORDER BY time DESC, seq_id DESC LIMIT 1 in a single index probe.

Follow-up questions

Similar questions

More Valon interview questions

All 8 Valon questions →