Annual Account Balance After Monthly Fee Waivers

Easy · Coding & Algorithms · Data Engineer · Online Assessment

Problem Statement

Simulate a checking account across a full 12-month calendar year (months 1 through 12) starting from initial_balance and return the closing balance after month 12:

def calculate_final_balance(initial_balance: float, transactions: List[Dict]) -> float:

Each entry in transactions is a dictionary with three keys:

  • "amount" (float): a positive dollar figure.
  • "month" (int): an integer in 1..12 identifying the calendar month of the activity.
  • "type" (str): either "payment" (subtracts "amount" from the balance) or "deposit" (adds "amount" to the balance).

Transactions may appear in arbitrary order, and the account balance is allowed to drop below 0.0 at any point.

At the close of every month from 1 to 12—including months with zero transactions—a $5.0 card maintenance fee is deducted from the balance unless that month earns a fee waiver. Month m earns the waiver if and only if both conditions hold within month m alone:

  1. At least 3 "payment" transactions occurred in month m, and
  2. The combined "amount" of those "payment" transactions in month m is strictly greater than 100.0 (> 100.0; spending 100.0 exactly does not qualify, and "deposit" entries never count toward either the count or the spending sum).

Return the account balance (float) after all transactions and all 12 monthly fee checks have been applied.

Examples

Example 1

Input:
  initial_balance = 300.0
  transactions = [
      {"amount": 45.0, "month": 3, "type": "payment"},
      {"amount": 35.0, "month": 3, "type": "payment"},
      {"amount": 30.0, "month": 3, "type": "payment"}
  ]

Output:
  135.0

Explanation: Month 3 has 3 payments totaling 45 + 35 + 30 = 110.0 (>= 3 payments and > 100.0), waiving month 3's fee. Each of the remaining 11 idle months charges $5.0 (55.0 total), leaving 300.0 - 110.0 - 55.0 = 135.0.

Example 2

Input:
  initial_balance = 400.0
  transactions = [
      {"amount": 25.0, "month": 5, "type": "payment"},
      {"amount": 150.0, "month": 5, "type": "deposit"},
      {"amount": 35.0, "month": 5, "type": "payment"},
      {"amount": 20.0, "month": 5, "type": "payment"}
  ]

Output:
  410.0

Explanation: Month 5 changes the balance by -25 + 150 - 35 - 20 = +70.0. Although 3 payments occurred in month 5, their payment sum is 25 + 35 + 20 = 80.0 <= 100.0 (the 150.0 deposit does not count toward spending), so month 5 still incurs the $5.0 fee. Across all 12 months, fees total 12 * 5.0 = 60.0, giving 400.0 + 70.0 - 60.0 = 410.0.

Example 3

Input:
  initial_balance = 250.0
  transactions = []

Output:
  190.0

Explanation: With zero activity all year, every month 1..12 deducts $5.0, ending at 250.0 - 60.0 = 190.0.

Constraints

  • 0.0 <= initial_balance <= 10^7
  • 0 <= len(transactions) <= 1000
  • Every transaction satisfies amount > 0, 1 <= month <= 12, and type in {"payment", "deposit"}.
  • Account balances may become negative during or at the end of the year.

Step-by-step walkthrough

  1. Understand the yearly rules

    We start the year with initial_balance dollars and a list of transactions. Each transaction is a dictionary with three fields:

    • "amount": positive dollar value (float),
    • "month": calendar month from 1 (January) to 12 (December),
    • "type": either "payment" (subtracts from the balance) or "deposit" (adds to the balance).

    Every single month from 1 to 12 follows two steps in order:

    1. Apply all payments and deposits belonging to that month.
    2. At the end of the month, subtract a $5 card fee unless that month had at least 3 payments whose total spending strictly exceeded $100.

    Even if a month has zero transactions in the input list, the account still exists during that month and still gets charged the $5 fee.

  2. Pin down the fee-waiver rule and the floating-point trap

    To waive the $5 fee for month m, two separate conditions must both be true in month m:

    • Payment count (>= 3): At least 3 transactions with type == "payment". Deposits never count, no matter how large they are.
    • Payment total (> 100): The sum of those payments must be strictly greater than $100. Spending $100.00 exactly does not waive the fee.

    Working with money in binary floating-point (float) hides a subtle trap right at the $100 boundary. Most decimal fractions like 0.2 or 83.9 cannot be stored with infinite precision in base 2. As a result:

    Decimal truth:    0.20 + 83.90 + 15.90 = 100.00          (NOT > 100 -> charge fee)
    Python float sum: 0.2  + 83.9  + 15.9  = 100.00000000000001  (> 100 -> wrong waiver!)
    

    Comparing monthly_payment_total[month] > 100.0 + EPSILON with EPSILON = 1e-9 (one billionth of a dollar) ignores tiny 16th-digit rounding noise while still treating every real cent above $100 (such as $100.01) as strictly greater than $100.

    # Fixed banking rules for the monthly card fee and its waiver threshold.
    MONTHLY_FEE = 5.0
    MIN_PAYMENTS = 3
    MIN_SPENDING = 100.0
    
    # Binary floats can turn exact $100.00 sums (like 0.2 + 83.9 + 15.9) into
    # 100.00000000000001; adding 1e-9 prevents false waivers while keeping $100.01 valid.
    EPSILON = 1e-9
    
  3. Bucket transactions by month in a single pass

    A brute-force simulation loops over month = 1..12 and scans the entire transactions list from start to finish each time (12 × n steps). Since n <= 1000, that would still run quickly, but grouping the transactions into 12 monthly buckets first is cleaner, runs in a single O(n) pass, and works even when the input list is not sorted by month.

    Because months are numbered 1 through 12, we can allocate three small lists of length 13 and leave index 0 unused so that month maps directly to its own index:

    Index:     0      1 (Jan)   ...   3 (Mar)   ...   5 (May)   ...   12 (Dec)
             +----+-----------+-----+-----------+-----+---------+-----+----------+
    net:     | -- |    0.0    | ... |  -110.0   | ... |  +70.0  | ... |    0.0   |  <- +deposits - payments
    count:   | -- |     0     | ... |     3     | ... |    3    | ... |     0    |  <- number of payments
    total:   | -- |    0.0    | ... |  +110.0   | ... |  +80.0  | ... |    0.0   |  <- sum of payment amounts
             +----+-----------+-----+-----------+-----+---------+-----+----------+
    
  4. Phase 1: Aggregate every transaction into its month

    As we scan transactions once:

    • A "payment" decreases monthly_net_change[month], adds 1 to monthly_payment_count[month], and adds amount to monthly_payment_total[month].
    • A "deposit" increases monthly_net_change[month] and leaves both payment trackers untouched.
    def group_by_month(transactions):
        monthly_net_change = [0.0] * 13
        monthly_payment_count = [0] * 13
        monthly_payment_total = [0.0] * 13
    
        for txn in transactions:
            month = txn["month"]
            amount = txn["amount"]
            txn_type = txn["type"]
    
            if txn_type == "payment":
                monthly_net_change[month] -= amount
                monthly_payment_count[month] += 1
                monthly_payment_total[month] += amount
            elif txn_type == "deposit":
                # Deposits raise the account balance but never count toward the fee waiver.
                monthly_net_change[month] += amount
            else:
                raise ValueError(f"Unknown transaction type: {txn_type}")
    
        return monthly_net_change, monthly_payment_count, monthly_payment_total
    
  5. Phase 2: Sweep through January to December

    Once the 12 buckets are filled, we start balance = float(initial_balance) and step month from 1 to 12:

    1. Add monthly_net_change[month] to apply all deposits and payments for that month.
    2. Check whether monthly_payment_count[month] >= MIN_PAYMENTS and monthly_payment_total[month] > MIN_SPENDING + EPSILON.
    3. If the waiver was not earned, subtract MONTHLY_FEE.

    Nothing in the rules blocks a payment or fee when the balance drops below zero—negative balances are explicitly allowed. Converting initial_balance with float(...) ensures the function always returns a float even if all inputs are plain integers.

  6. Trace the three examples

    Example 1: initial_balance = 300.0, Mar has 3 payments: 45, 35, 30
      Months 1..2:   0 payments -> 2 * $5.0 = $10.0 fees (balance = 290.0)
      Month 3 (Mar): balance = 290.0 - 110.0 = 180.0
                     count = 3 (>= 3), total = 110.0 (> 100) -> FEE WAIVED
      Months 4..12:  net = 0, count = 0 -> $5.0 fee charged in each of the 9 months
      Year-end:      180.0 - (9 * 5.0) = 135.0
    
    Example 2: initial_balance = 400.0, May has payments 25, 35, 20 and deposit 150
      Months 1..4:   4 * $5.0 = $20.0 fees -> balance = 380.0
      Month 5 (May): 380.0 - 80.0 + 150.0 = 450.0
                     count = 3 (>= 3), but payment total = 80.0 (<= 100) -> $5.0 FEE CHARGED (445.0)
                     (the $150 deposit increases the balance, NOT the payment total!)
      Months 6..12:  7 more $5.0 fees -> 445.0 - 35.0 = 410.0
    
    Example 3: initial_balance = 250.0, transactions = []
      Months 1..12:  0 payments every month -> $5.0 fee charged all 12 months
      Year-end:      250.0 - (12 * 5.0) = 190.0
    
  7. Complete solution

    Putting both phases directly inside calculate_final_balance gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Fixed banking rules for the monthly card fee and its waiver threshold.
    MONTHLY_FEE = 5.0
    MIN_PAYMENTS = 3
    MIN_SPENDING = 100.0
    
    # Binary floats can turn exact $100.00 sums (like 0.2 + 83.9 + 15.9) into
    # 100.00000000000001; adding 1e-9 prevents false waivers while keeping $100.01 valid.
    EPSILON = 1e-9
    
    
    def calculate_final_balance(initial_balance: float, transactions: List[Dict]) -> float:
        # Per-month buckets indexed by month 1..12 (index 0 is unused padding):
        # - monthly_net_change[m]: signed dollar delta (+deposits, -payments) in month m
        # - monthly_payment_count[m]: count of "payment" transactions in month m
        # - monthly_payment_total[m]: total dollars spent across "payment" transactions in month m
        monthly_net_change = [0.0] * 13
        monthly_payment_count = [0] * 13
        monthly_payment_total = [0.0] * 13
    
        # Phase 1: Group every transaction into its calendar month bucket in one pass.
        for txn in transactions:
            month = txn["month"]
            amount = txn["amount"]
            txn_type = txn["type"]
    
            if txn_type == "payment":
                monthly_net_change[month] -= amount
                monthly_payment_count[month] += 1
                monthly_payment_total[month] += amount
            elif txn_type == "deposit":
                # Deposits raise the account balance but never count toward the fee waiver.
                monthly_net_change[month] += amount
            else:
                raise ValueError(f"Unknown transaction type: {txn_type}")
    
        # Phase 2: Simulate months 1..12 in order, including idle months with zero activity.
        balance = float(initial_balance)
        for month in range(1, 13):
            balance += monthly_net_change[month]
    
            # Both conditions must hold in the same month; spending must be strictly > $100.
            has_enough_payments = monthly_payment_count[month] >= MIN_PAYMENTS
            has_enough_spending = monthly_payment_total[month] > MIN_SPENDING + EPSILON
            fee_waived = has_enough_payments and has_enough_spending
    
            if not fee_waived:
                balance -= MONTHLY_FEE
    
        return balance
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the input as a shoebox of unsorted receipts and deposit slips from the entire year. Instead of hunting through the whole shoebox twelve separate times, you set out 12 folders labeled January through December, drop each slip into its matching month's folder while tallying that month's payment count and payment spending, and then walk calmly from January to December updating your running balance and deciding whether each month owes the $5 card fee.

A naive approach that only loops over months appearing in transactions fails immediately because idle months with zero transactions still get charged $5. Rescanning the whole list once per month works for small inputs (12 × n checks) but wastes work compared to bucketing in a single pass. Even subtler, comparing raw binary floating-point sums directly with > 100 can fail because floating-point rounding error (tiny base-2 representation inaccuracies when storing decimal cents) can make an exact $100.00 sum like 0.2 + 83.9 + 15.9 evaluate to 100.00000000000001; adding a tiny epsilon tolerance (a small safety margin 1e-9 added to the threshold) prevents that false waiver while still accepting $100.01.

Here is how a tiny trace works on Example 1 (initial_balance = 300.0 with three March payments of 45.0, 35.0, and 30.0):

  1. Bucket pass: Month 3 records monthly_net_change[3] = -110.0, monthly_payment_count[3] = 3, and monthly_payment_total[3] = 110.0. All other months stay at zero.
  2. March (month = 3): After January and February each deduct $5.0 (290.0), March subtracts 110.0 to reach 180.0. Because 3 >= 3 and 110.0 > 100.0 + 1e-9, March's $5 fee is waived.
  3. Remaining months (month = 4..12): Each of the remaining 9 months has 0 payments and subtracts $5.0, leaving 180.0 - 9 × 5.0 = 135.0.

Complexity

  • Time: O(n), where n is the number of transactions. We scan the n transactions once with O(1) array updates per transaction, and then run a fixed 12-iteration loop over the months of the year.
  • Space: O(1) auxiliary memory. Regardless of how many transactions arrive, we only allocate three fixed-size lists of 13 numbers (monthly_net_change, monthly_payment_count, and monthly_payment_total).

Edge cases

  • Empty transaction list ([]): Every month from January to December has 0 payments, so all 12 fees apply and the final balance is initial_balance - 60.0 (Example 3).
  • Months with deposits only: Deposits raise monthly_net_change without increasing monthly_payment_count or monthly_payment_total, so the $5 fee still applies.
  • Spending of exactly $100.00: The rule says spending must exceed $100 (> 100, not >= 100), so three payments of 30 + 30 + 40 = 100 still pay the $5 fee.
  • Floating-point rounding right at $100.00: Payments 0.2 + 83.9 + 15.9 total $100.00 exactly in decimal but 100.00000000000001 in binary float; testing > 100.0 + 1e-9 keeps the fee in place.
  • Meeting only one of the two conditions: Two large payments (300 + 300) fail count >= 3, and five small payments (5 × 15 = 75) fail total > 100; both pay the fee.
  • Out-of-order transactions: Because Phase 1 indexes directly by txn["month"], transactions in December appearing before January are still tallied accurately.
  • Negative balances: An account is allowed to dip below 0.0 from either payments or monthly fees.

Common mistakes

  • Skipping months that have no transactions: Checking fees only for keys present in a dictionary misses empty months and undercharges by $5 per missing month.
  • Counting deposits toward the waiver: Letting a $150 deposit count as a payment or boost monthly_payment_total fails Example 2.
  • Using >= 100 instead of > 100, or or instead of and: Both conditions must hold simultaneously, and $100 is a strict lower bound.
  • Forgetting to reset counters between months: Carrying January's payment count or spending over into February waives fees that were never earned.
  • Comparing raw floats against 100 without an epsilon (or exact decimal representation): In production banking code, storing money as integer cents (int) or Decimal avoids binary float issues altogether; when an API mandates float, an epsilon guard protects exact thresholds.

Follow-up questions

  • How would your implementation change if each month's fee depended on the account's current balance tier? Our two-phase structure already processes months 1 through 12 in chronological order, which becomes mandatory once month m's fee depends on the end-of-month balance balance (for example, $0 if balance >= 10000, $5 if balance >= 1000, and $15 otherwise). At the end of each month, after adding monthly_net_change[month], we would evaluate fee = fee_schedule(balance) if not fee_waived and subtract it before moving to month + 1. If the bank instead bases the fee on average daily balance, each transaction would also need a day field so we could weight each balance level by the number of days it was held.
  • How would you scale this calculation to hundreds of millions of ledger rows across many accounts in Spark or SQL? In a distributed engine like Apache Spark or SQL, we can run a two-stage aggregation partitioned by (account_id, month). First, each worker performs map-side pre-aggregation (summing net_change, payment_count, and payment_total locally per (account_id, month) before sending data across the network during a shuffle, which is the step that redistributes rows by key across machines). That shrinks millions of raw transactions down to at most 12 tiny summary rows per account, which a second group-by on account_id folds across months 1..12 locally—ideally using integer cents or DECIMAL(18, 2) instead of binary floats.
  • How would you adapt the algorithm if fee waivers were evaluated over a two-month sliding window? Keep the exact same Phase 1 arrays, and in Phase 2 check monthly_payment_count[month - 1] + monthly_payment_count[month] >= 3 and monthly_payment_total[month - 1] + monthly_payment_total[month] > 100.0 + EPSILON. Leaving index 0 at 0 naturally makes January look only at January unless December of the previous calendar year is passed in as an extra input, which you should clarify with the interviewer. If the rolling window generalized to w consecutive months, maintaining a prefix sum (an array where entry m stores the cumulative total from month 1 through month m so any range sum takes a single subtraction) keeps every window check O(1).

Follow-up questions

Similar questions

More DRW interview questions

All 30 DRW questions →