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 in1..12identifying 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:
- At least
3"payment"transactions occurred in monthm, and - The combined
"amount"of those"payment"transactions in monthmis strictly greater than100.0(> 100.0; spending100.0exactly 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^70 <= len(transactions) <= 1000- Every transaction satisfies
amount > 0,1 <= month <= 12, andtype in {"payment", "deposit"}. - Account balances may become negative during or at the end of the year.
Step-by-step walkthrough
Understand the yearly rules
We start the year with
initial_balancedollars and a list oftransactions. Each transaction is a dictionary with three fields:"amount": positive dollar value (float),"month": calendar month from1(January) to12(December),"type": either"payment"(subtracts from the balance) or"deposit"(adds to the balance).
Every single month from
1to12follows two steps in order:- Apply all payments and deposits belonging to that month.
- 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.
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 monthm:- Payment count (
>= 3): At least 3 transactions withtype == "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.00exactly does not waive the fee.
Working with money in binary floating-point (
float) hides a subtle trap right at the$100boundary. Most decimal fractions like0.2or83.9cannot 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 + EPSILONwithEPSILON = 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- Payment count (
Bucket transactions by month in a single pass
A brute-force simulation loops over
month = 1..12and scans the entiretransactionslist from start to finish each time (12 × nsteps). Sincen <= 1000, that would still run quickly, but grouping the transactions into 12 monthly buckets first is cleaner, runs in a singleO(n)pass, and works even when the input list is not sorted by month.Because months are numbered
1through12, we can allocate three small lists of length13and leave index0unused so thatmonthmaps 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 +----+-----------+-----+-----------+-----+---------+-----+----------+Phase 1: Aggregate every transaction into its month
As we scan
transactionsonce:- A
"payment"decreasesmonthly_net_change[month], adds1tomonthly_payment_count[month], and addsamounttomonthly_payment_total[month]. - A
"deposit"increasesmonthly_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- A
Phase 2: Sweep through January to December
Once the 12 buckets are filled, we start
balance = float(initial_balance)and stepmonthfrom1to12:- Add
monthly_net_change[month]to apply all deposits and payments for that month. - Check whether
monthly_payment_count[month] >= MIN_PAYMENTSandmonthly_payment_total[month] > MIN_SPENDING + EPSILON. - 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_balancewithfloat(...)ensures the function always returns afloateven if all inputs are plain integers.- Add
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.0Complete solution
Putting both phases directly inside
calculate_final_balancegives 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):
- Bucket pass: Month
3recordsmonthly_net_change[3] = -110.0,monthly_payment_count[3] = 3, andmonthly_payment_total[3] = 110.0. All other months stay at zero. - March (
month = 3): After January and February each deduct$5.0(290.0), March subtracts110.0to reach180.0. Because3 >= 3and110.0 > 100.0 + 1e-9, March's $5 fee is waived. - Remaining months (
month = 4..12): Each of the remaining9months has0payments and subtracts$5.0, leaving180.0 - 9 × 5.0 = 135.0.
Complexity
- Time:
O(n), wherenis the number of transactions. We scan thentransactions once withO(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, andmonthly_payment_total).
Edge cases
- Empty transaction list (
[]): Every month from January to December has0payments, so all 12 fees apply and the final balance isinitial_balance - 60.0(Example 3). - Months with deposits only: Deposits raise
monthly_net_changewithout increasingmonthly_payment_countormonthly_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 of30 + 30 + 40 = 100still pay the $5 fee. - Floating-point rounding right at
$100.00: Payments0.2 + 83.9 + 15.9total$100.00exactly in decimal but100.00000000000001in binary float; testing> 100.0 + 1e-9keeps the fee in place. - Meeting only one of the two conditions: Two large payments (
300 + 300) failcount >= 3, and five small payments (5 × 15 = 75) failtotal > 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.0from 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
$150deposit count as a payment or boostmonthly_payment_totalfails Example 2. - Using
>= 100instead of> 100, ororinstead ofand: Both conditions must hold simultaneously, and$100is 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
100without an epsilon (or exact decimal representation): In production banking code, storing money as integer cents (int) orDecimalavoids binary float issues altogether; when an API mandatesfloat, 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
1through12in chronological order, which becomes mandatory once monthm's fee depends on the end-of-month balancebalance(for example,$0ifbalance >= 10000,$5ifbalance >= 1000, and$15otherwise). At the end of each month, after addingmonthly_net_change[month], we would evaluatefee = fee_schedule(balance)ifnot fee_waivedand subtract it before moving tomonth + 1. If the bank instead bases the fee on average daily balance, each transaction would also need adayfield 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 (summingnet_change,payment_count, andpayment_totallocally 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 onaccount_idfolds across months1..12locally—ideally using integer cents orDECIMAL(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] >= 3andmonthly_payment_total[month - 1] + monthly_payment_total[month] > 100.0 + EPSILON. Leaving index0at0naturally 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 towconsecutive months, maintaining a prefix sum (an array where entrymstores the cumulative total from month1through monthmso any range sum takes a single subtraction) keeps every window checkO(1).
Follow-up questions
- How would your implementation change if each month's fee depended on the account's current balance tier?
- How would you scale this calculation to hundreds of millions of ledger rows across many accounts in Spark or SQL?
- How would you adapt the algorithm if fee waivers were evaluated over a two-month sliding window?
Similar questions
- Minimum Deletions to Prevent Consecutive Triples
- Minimum Postponed Debits for Non-Negative Ledger
- Scoped Nested Transactions for a Key-Value Store
- Maximum Even-Frequency Subsequence of Ones and Twos
- Longest Substring With Uniform Character Counts
- Largest Even-Parity Subsequence of Ones and Twos
More DRW interview questions
- Maximum Even-Frequency Subsequence of Ones and Twos Medium
- Expected Target Score for Isotropic Gaussian Throws Hard
- Stopping Time and Absorption Odds for Two Cart Queues Hard Pro
- Conditional Flip Count When HHT Beats HTH Hard Pro
- Prize Collection Odds on a 45-Node Ring Hard Pro
- Minimum Postponed Debits for Non-Negative Ledger Easy Pro
- Scoped Nested Transactions for a Key-Value Store Easy Pro
- Longest Substring With Uniform Character Counts Easy Pro
- Largest Even-Parity Subsequence of Ones and Twos Hard Pro
- Smallest Array Spread Within Three Element Edits Easy Pro