Card Settlement Batch with Fees, Rebates and Duplicate Guard
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a ledger: order card transactions by time, compute integer fee and rebate, enforce balance limits, and flag repeated transaction IDs.
Settling a Batch of Card Transactions
A company card platform receives a batch of settled card payments and must apply them to business account balances. Each payment may carry a flat processing fee and may earn a percentage rebate, depending on its merchant category. Write a function that settles the whole batch and reports what happened to each payment.
Inputs
transactions: a list of dictionaries, each with:txn_id(str): the transaction identifier.account_id(str): the business account that pays.merchant_category(str): the category of the merchant, such as"SAAS","TRAVEL"or"OFFICE".amount_cents(int): the base amount in cents (positive).timestamp(int): Unix time in seconds.
merchant_rules: a dictionary mapping each merchant category to a rule dictionary with:rebate_bps(int): rebate rate in basis points (1 bp = 0.01%).surcharge_cents(int): a flat fee in cents added to the payment.exempt_threshold_cents(int): the fee is waived whenamount_centsis strictly greater than this value.
account_balances: a dictionary mapping eachaccount_idto its available balance in cents (int).
Rules
- Processing order. Handle transactions in ascending
timestamp. If timestamps are equal, order bytxn_idusing ordinary string comparison (so"tx_10"comes before"tx_2"). - Cost of a transaction.
feeis0ifamount_cents > exempt_threshold_cents; otherwise it issurcharge_cents. An amount exactly equal to the threshold still pays the fee.rebate = floor(amount_cents * rebate_bps / 10000), computed with integers only.net_cost = amount_cents + fee - rebate.
- Funds check. If the account's current balance is less than
net_cost, the transaction is"DECLINED_INSUFFICIENT_FUNDS"and the balance does not change. A balance exactly equal tonet_costis sufficient. Otherwise the transaction is"PROCESSED"andnet_costis subtracted from the balance. Balances are updated as the batch is processed, so earlier transactions affect later ones. - Duplicates. Once a
txn_idhas been encountered in processing order, it is used up, whether that first occurrence was processed or declined. Every later transaction with the sametxn_idgets status"DUPLICATE"and has no effect on any balance. Note that the "first" occurrence is the first one in processing order, not in the input list.
Output
Return a two-element list [results, updated_balances]:
results: a list, in processing order, of dictionaries{"txn_id": str, "status": str, "net_cost_cents": int}. The status is one of"PROCESSED","DECLINED_INSUFFICIENT_FUNDS"or"DUPLICATE".net_cost_centsis the computed net cost for"PROCESSED"entries and0for the others.updated_balances: a new dictionary with the final balance of every account. The inputaccount_balancesmust not be modified.
Constraints
- Every
merchant_categoryused by a transaction appears inmerchant_rules, and everyaccount_idappears inaccount_balances. amount_centsis a positive integer;rebate_bps,surcharge_cents,exempt_threshold_centsand balances are non-negative integers.- The batch may be empty, in which case the result is
[[], copy_of_balances]. - Use integer arithmetic only; do not use floating-point numbers for the rebate.
- The input lists and dictionaries should not be mutated.
Examples
Example 1
Input: settle_card_batch([{'txn_id': 'tx_2', 'account_id': 'acc_1', 'merchant_category': 'SAAS', 'amount_cents': 10000, 'timestamp': 105}, {'txn_id': 'tx_1', 'account_id': 'acc_1', 'merchant_category': 'SAAS', 'amount_cents': 5000, 'timestamp': 100}, {'txn_id': 'tx_1', 'account_id': 'acc_1', 'merchant_category': 'SAAS', 'amount_cents': 5000, 'timestamp': 110}], {'SAAS': {'rebate_bps': 150, 'surcharge_cents': 200, 'exempt_threshold_cents': 8000}}, {'acc_1': 6000})
Output: [[{'txn_id': 'tx_1', 'status': 'PROCESSED', 'net_cost_cents': 5125}, {'txn_id': 'tx_2', 'status': 'DECLINED_INSUFFICIENT_FUNDS', 'net_cost_cents': 0}, {'txn_id': 'tx_1', 'status': 'DUPLICATE', 'net_cost_cents': 0}], {'acc_1': 875}]
Hints
Hint 1
Sort a copy of the transactions by the pair (timestamp, txn_id) before doing anything else, because 'first occurrence' is defined by processing order.
Hint 2
Keep a set of txn_ids already seen. Add an id the first time you meet it regardless of whether the payment is processed or declined.
Hint 3
Compute the rebate as amount * bps // 10000 to stay in integers, and use a strict greater-than when testing the fee waiver. Work on a copy of the balances dictionary.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a deterministic ledger simulation. The three pieces that matter are ordering, duplicate detection and exact arithmetic.
- Sort first. Sort a copy of the transactions by
(timestamp, txn_id). Tuple comparison handles the tie-break ontxn_idas a plain string comparison. Sorting before deduplicating guarantees that the "first" occurrence of an id is the earliest one in processing order, not the earliest in the input list. - Walk the sorted list once. Keep a
seenset of ids and a copied balances dictionary.- If the id is already in
seen, emit aDUPLICATEresult with cost 0 and move on. - Otherwise add the id to
seenimmediately, even if the payment ends up declined, so a later repeat of a declined id is still a duplicate and never retried. - Look up the merchant rule. The fee is
0whenamount > exempt_threshold_cents(strict), otherwisesurcharge_cents. The rebate isamount * rebate_bps // 10000, which multiplies before dividing and uses floor division, so no floats are involved. net_cost = amount + fee - rebate. If the account balance is less thannet_cost, emitDECLINED_INSUFFICIENT_FUNDSwith cost 0 and leave the balance alone. Otherwise subtract the cost and emitPROCESSEDwith the cost.
- If the id is already in
- Return
[results, balances], wherebalancesis the copy, so the caller's input is never mutated.
Why it is correct
- Sorting implements the required order exactly, and
sortedleaves the input list untouched. - Because ids are marked as seen on first encounter in sorted order, the duplicate rule matches the specification regardless of outcome of the first occurrence.
- Integer floor division gives the exact floor of the rational rebate, avoiding floating-point error.
- The strict
>comparison keeps the fee for amounts equal to the threshold, and the<funds check allows a balance that exactly equals the cost. - Balances change only in the processed branch, so declines and duplicates cannot alter state.
Complexity
- Time: O(N log N) for the sort plus O(N) for the pass, with O(1) set and dictionary operations.
- Space: O(N) for the sorted copy, the seen set and the results, plus O(A) for the copied balances (A accounts).
Reference solution
from typing import Dict, List
def settle_card_batch(transactions: List[Dict], merchant_rules: Dict, account_balances: Dict) -> List:
balances = dict(account_balances)
results = []
seen = set()
for txn in sorted(transactions, key=lambda t: (t["timestamp"], t["txn_id"])):
txn_id = txn["txn_id"]
if txn_id in seen:
results.append({"txn_id": txn_id, "status": "DUPLICATE", "net_cost_cents": 0})
continue
seen.add(txn_id)
rule = merchant_rules[txn["merchant_category"]]
amount = txn["amount_cents"]
fee = 0 if amount > rule["exempt_threshold_cents"] else rule["surcharge_cents"]
rebate = amount * rule["rebate_bps"] // 10000
net_cost = amount + fee - rebate
account_id = txn["account_id"]
if balances[account_id] < net_cost:
results.append({"txn_id": txn_id, "status": "DECLINED_INSUFFICIENT_FUNDS", "net_cost_cents": 0})
else:
balances[account_id] -= net_cost
results.append({"txn_id": txn_id, "status": "PROCESSED", "net_cost_cents": net_cost})
return [results, balances]