Group Expense Ledger and Minimum-Transfer Settlement
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
A group of friends sharing a weekend cabin trip needs a backend service to record shared bills—such as groceries, firewood, and kayak rentals—and figure out who should pay whom at the end of the trip. Whenever someone pays a bill, they log the total charge and how that charge is divided among participants. From those records, the service computes a single signed net balance (in integer cents) for each participant within the group:
- A positive value means the participant covered more than their share and is owed that many cents back.
- A negative value means the participant owes that many cents toward the group's bills.
- A zero value means the participant is already settled up.
Because every cent paid by someone is assigned to someone's share, the net balances across a group always sum to 0.
This problem has two parts:
- System & API Design: Outline the core domain models, public service endpoints, and data-integrity guarantees needed for a production shared-expense service:
- Support independent expense groups (so two people who belong to multiple trips keep separate per-group balances), flexible split rules (equal division, exact cent amounts, percentage splits, and weighted share ratios), and single-currency integer-cent accounting with deterministic penny allocation when a bill does not divide evenly.
- Guarantee that network retries never lose or duplicate bills or payments, concurrent writes cannot corrupt balances, and generating a suggested settlement preview never mutates stored balances or creates fake payment records (kept strictly separate from an append-only log of actual completed transfers).
- Settlement Algorithms: Implement two pure functions (without mutating the input dictionary):
settle(balances: Dict[str, int]) -> List[List[object]]: Partition participants with negative balances (debtors) and positive balances (creditors) in the iteration order ofbalances, skipping anyone with a0balance, and greedily pair the current debtor with the current creditor by transferringmin(remaining_debt, remaining_credit)until every balance reaches0. Return each transfer as[payer, payee, amount]. (The automated judge evaluatessettle.)settle_optimally(balances: Dict[str, int]) -> List[List[object]]: Return a valid list of[payer, payee, amount]transfers that brings every participant's balance to0using the smallest possible number of transfers.
def settle(balances: Dict[str, int]) -> List[List[object]]:
pass
Examples
Example 1
Input: balances = {"Leo": 900, "Nora": 300, "Omar": -300, "Zoe": -900}
Output (settle): [["Omar", "Leo", 300], ["Zoe", "Leo", 600], ["Zoe", "Nora", 300]]
Output (settle_optimally): [["Zoe", "Leo", 900], ["Omar", "Nora", 300]] (any 2-transfer valid plan)
Walk-through: Suppose Leo paid 1200 cents split four ways (300 each), Nora paid 900 cents split among Nora, Omar, and Zoe (300 each), and Omar paid 600 cents split between Omar and Zoe (300 each). Their net balances are Leo: +900, Nora: +300, Omar: -300, and Zoe: -900.
- In settle, debtors in input order are Omar (300) then Zoe (900), and creditors are Leo (900) then Nora (300). Omar pays Leo 300 (clearing Omar and leaving Leo owed 600), Zoe pays Leo 600 (clearing Leo and leaving Zoe owing 300), and finally Zoe pays Nora 300, taking 3 transfers total.
- In settle_optimally, Zoe pays Leo 900 directly and Omar pays Nora 300 directly, clearing all four balances in just 2 transfers.
Example 2
Input: balances = {"Dana": -400, "Eli": 0, "Finn": -650, "Gwen": 1050}
Output (settle): [["Dana", "Gwen", 400], ["Finn", "Gwen", 650]]
Walk-through: Eli already has a 0 balance and is skipped. Dana pays Gwen 400 cents (reducing Gwen's remaining credit to 650), and then Finn pays Gwen 650 cents, leaving everyone at 0. Here 2 transfers is also the theoretical minimum.
Constraints
0 <= len(balances) <= 12forsettle_optimally(settleruns in linear time for any group size).- Every key in
balancesis a unique non-empty participant identifier (str), and every value is a signed integer in cents (int). sum(balances.values()) == 0.- Every returned transfer
[payer, payee, amount]must reference distinct participants inbalanceswith a strictly positive integeramount > 0, and neither function may mutatebalances.
Step-by-step walkthrough
Understand the net-balance model and the two settlement goals
When friends share bills on a cabin trip, tracking a separate IOU between every pair of people quickly turns into a tangled web of payments. Instead, we can imagine a central group pot:
- A positive net balance (
+900) means the pot owes that participant 900 cents (they paid more than their share). We call them a creditor. - A negative net balance (
-300) means that participant owes the pot 300 cents (others covered their share). We call them a debtor. - Because every cent paid into a shared bill is assigned to someone in the group, all net balances always add up to
0.
Cabin trip bills (in cents): Leo pays 1200 split 4 ways (300 each) -> Leo +900, Nora -300, Omar -300, Zoe -300 Nora pays 900 split 3 ways (300 each) -> Nora +600, Omar -300, Zoe -300 Omar pays 600 split 2 ways (300 each) -> Omar +300, Zoe -300 ----------------------------------------------------------------------------------- Running net balances: Leo: +900, Nora: +300, Omar: -300, Zoe: -900Both settlement functions take
balances: Dict[str, int](in integer cents, so floating-point rounding never corrupts money) and return a list of[payer, payee, amount]transfers without mutatingbalances:settle(balances)pairs debtors and creditors greedily in input dictionary order (the automated judge checkssettle).settle_optimally(balances)finds a valid plan using the fewest possible transfers (2transfers on Example 1 instead of3).
- A positive net balance (
Part 1: Design the entities, API, and money-safety rules
Before writing the algorithms, Part 1 asks how the surrounding expense-tracker service keeps balances accurate when real people log bills and send money concurrently.
The cleanest architecture separates append-only facts (logged bills and real-money transfers that actually happened) from derived views (current balances and preview settlement plans):
+--------------------+ +-----------------------+ | Expense | | ExpenseShare | | - id |1 *| - expense_id | | - group_id |------>| - member_id | | - paid_by | | - share_cents | | - amount_cents | +-----------------------+ | - idempotency_key | +--------------------+ \ \ derived net balance(m) = +--> (expenses m paid - shares m owed) + (transfers m sent - transfers m received) / +--------------------+ | Transfer | <-- append-only log of REAL payments actually made | - id, group_id | | - payer, payee | | - amount_cents | | - idempotency_key | +--------------------+Public API sketch:
add_expense(group_id, paid_by, amount_cents, split_spec, idempotency_key) -> expense_id(supportsEQUAL,EXACT,PERCENT, and weightedSHARESsplits, scoped per group).get_balances(group_id) -> Dict[member_id, int](derived read-only snapshot in cents).plan_settlement(group_id, optimal: bool) -> List[[payer, payee, cents]](pure preview — writes nothing to the database).record_transfer(group_id, payer, payee, amount_cents, idempotency_key) -> transfer_id(records an actual payment).get_history(group_id, member_id) -> List[Expense | Transfer](chronological audit trail).
Four non-functional guarantees protect users' money:
- No lost or double-counted writes: Clients attach a unique
idempotency_key(a request ID generated once per button tap) so network retries return the existing record instead of charging twice. - Concurrency safety: Balances are derived from the append-only logs. If cached in a
GroupBalancerow, update them inside the same database transaction using atomic SQL increments (SET balance_cents = balance_cents + delta), never an application-level read-modify-write that could lose a concurrent update. - Deterministic cent rounding: Resolve percentages or uneven splits into integer cents at write time (for example,
1000cents split 3 ways becomes334, 333, 333, assigning leftover pennies in sortedmember_idorder) sosum(share_cents) == amount_centsalways holds. - Preview vs. execution separation: Calling
settleorsettle_optimallynever mutates stored balances; onlyrecord_transferrecords real money movement.
Part 2a: Greedy two-pointer settlement (`settle`)
To settle balances simply and predictably, split participants into two lists while preserving input order:
debtors:[name, -balance]for everyone withbalance < 0(flipping the sign sodebt_leftis positive).creditors:[name, balance]for everyone withbalance > 0.- Participants with
balance == 0(such as"Eli"in Example 2) are skipped completely.
Now maintain two pointers,
debtor_idxandcreditor_idx. At each step, the current debtor pays the current creditormin(debt_left, credit_left):- Neither person ever overshoots
0, because we cap the transfer at the smaller of the two remaining amounts. - At least one of the two remaining amounts drops to
0, so at least one pointer moves forward on every iteration. - Because total debt equals total credit, both lists finish at the exact same moment!
One critical detail: use two separate
ifchecks (notelif) when advancingdebtor_idxandcreditor_idx. Whendebt_left == credit_left, a single transfer settles both people at once — if only one pointer moved, the next loop iteration would emit a bogus0-cent payment!def settle(balances: Dict[str, int]) -> List[List[object]]: """Return a valid list of [payer, payee, amount] transfers using greedy pairing.""" # debtors: list of [member_name, cents_still_owed_by_member], e.g. [["Omar", 300], ["Zoe", 900]] debtors: List[List[Any]] = [] # creditors: list of [member_name, cents_still_owed_to_member], e.g. [["Leo", 900], ["Nora", 300]] creditors: List[List[Any]] = [] # Phase 1: Partition non-zero balances in input order without mutating the caller's dict. for name, balance in balances.items(): if balance < 0: # Flip the negative balance into a positive amount the debtor needs to pay out. debtors.append([name, -balance]) elif balance > 0: creditors.append([name, balance]) # Phase 2: Greedily match the current debtor with the current creditor. payments: List[List[object]] = [] debtor_idx = 0 creditor_idx = 0 while debtor_idx < len(debtors) and creditor_idx < len(creditors): debtor_name, debt_left = debtors[debtor_idx] creditor_name, credit_left = creditors[creditor_idx] # Transfer as much as possible without making either side overshoot zero. payment_cents = min(debt_left, credit_left) payments.append([debtor_name, creditor_name, payment_cents]) debtors[debtor_idx][1] -= payment_cents creditors[creditor_idx][1] -= payment_cents # Use two separate `if` checks (not `elif`): when debt_left == credit_left, # both sides reach 0 on the same transfer and both pointers must advance. if debtors[debtor_idx][1] == 0: debtor_idx += 1 if creditors[creditor_idx][1] == 0: creditor_idx += 1 return paymentsTrace `settle` on Example 1
On
{'Leo': 900, 'Nora': 300, 'Omar': -300, 'Zoe': -900}, input order givesdebtors = [['Omar', 300], ['Zoe', 900]]andcreditors = [['Leo', 900], ['Nora', 300]]:Step Current debtor Current creditor Transfer Remaining after step ---- -------------- ---------------- --------------------- ---------------------------------- 1 Omar (300) Leo (900) [Omar, Leo, 300] Omar: 0 (advance), Leo: 600 2 Zoe (900) Leo (600) [Zoe, Leo, 600] Zoe: 300, Leo: 0 (advance) 3 Zoe (300) Nora (300) [Zoe, Nora, 300] Zoe: 0 (advance), Nora: 0 (advance)settlereturns[['Omar', 'Leo', 300], ['Zoe', 'Leo', 600], ['Zoe', 'Nora', 300]]— valid andO(n)fast, though it took3transfers when2would suffice.Why greedy uses extra transfers: zero-sum groups
Why can Example 1 be settled in
2transfers instead of3? Look at the two settlement graphs side by side:Greedy pairing (1 connected group of 4 people -> 4 - 1 = 3 transfers): Omar (-300) --300--> Leo (+900) <--600-- Zoe (-900) --300--> Nora (+300) Optimal pairing (2 independent zero-sum groups -> 4 - 2 = 2 transfers): Group 1: Zoe (-900) --900--> Leo (+900) (sum = -900 + 900 = 0, 1 transfer) Group 2: Omar (-300) --300--> Nora (+300) (sum = -300 + 300 = 0, 1 transfer)Suppose there are
npeople with non-zero balances. Think of people as nodes and transfers as edges:- Money never leaves a connected component of transfers, so the balances inside every connected component must sum to
0. - Connecting
mpeople into one component takes at leastm - 1transfers (a tree onmnodes hasm - 1edges).
If the
nnon-zero balances can be split into at mostGdisjoint zero-sum groups of sizesm_1, m_2, ..., m_G, then the minimum number of transfers is:(m_1 - 1) + (m_2 - 1) + ... + (m_G - 1) = n - GFinding whether any subset sums to
0is the classic subset-sum problem (NP-hard in general), which is why no simple greedy sorting rule always finds the optimum. Fortunately, typical shared-expense groups have smalln, so backtracking with pruning solves it cleanly.- Money never leaves a connected component of transfers, so the balances inside every connected component must sum to
Part 2b: Backtracking with branch-and-bound (`settle_optimally`)
To search all relevant plans without wasting work,
settle_optimallyprocesses the non-zeroamountslist from left to right:- Advance
startpast any entries that are already0. Ifstart == len(amounts), every balance is settled — savecurrent_planif it beatsbest_plan. - Prune early (branch and bound): We initialize
best_plan = settle(balances). Sinceamounts[start]is non-zero, at least1more transfer is required. Wheneverlen(current_plan) + 1 >= len(best_plan), this branch cannot possibly produce fewer transfers thanbest_plan, so return immediately! - Try every opposite-sign partner
other > start: Shiftstart's entire balance ontootherin a single transfer (amounts[other] += start_amount,amounts[start] = 0), recurse onstart + 1, and undo the change afterward.
Why is shifting
start's entire balance onto a single opposite-sign partner guaranteed to include an optimal plan? In any optimal zero-sum group containingstart, all other members of that group sit at indices> start, and because the group sums to0, at least one memberotherinstart's group has the opposite sign. Transferringstart's balance onto thatotheruses1transfer, removesstart, and leaves the rest ofstart's group still summing to0— staying right on an optimaln - Gtrajectory!Example 1 search trace on amounts = [Leo +900, Nora +300, Omar -300, Zoe -900], initial best = 3: start=0 (Leo +900): -> pair with Omar (-300): Omar pays Leo 900 -> amounts = [0, +300, +600, -900] (1 transfer) start=1 (Nora +300): -> pair with Zoe (-900): len(current_plan)=1, after Nora<->Zoe len=2, still unsettled -> pruned at 2+1 >= 3! -> pair with Zoe (-900): Zoe pays Leo 900 -> amounts = [0, +300, -300, 0] (1 transfer) start=1 (Nora +300): -> pair with Omar (-300): Omar pays Nora 300 -> amounts = [0, 0, 0, 0] (2 transfers < 3 -> new best!)- Advance
Complete solution
Putting both
settle(called by the judge) andsettle_optimallytogether:from typing import Any, Dict, List, Optional, Set, Tuple def settle(balances: Dict[str, int]) -> List[List[object]]: """Return a valid list of [payer, payee, amount] transfers using greedy pairing.""" # debtors: list of [member_name, cents_still_owed_by_member], e.g. [["Omar", 300], ["Zoe", 900]] debtors: List[List[Any]] = [] # creditors: list of [member_name, cents_still_owed_to_member], e.g. [["Leo", 900], ["Nora", 300]] creditors: List[List[Any]] = [] # Phase 1: Partition non-zero balances in input order without mutating the caller's dict. for name, balance in balances.items(): if balance < 0: # Flip the negative balance into a positive amount the debtor needs to pay out. debtors.append([name, -balance]) elif balance > 0: creditors.append([name, balance]) # Phase 2: Greedily match the current debtor with the current creditor. payments: List[List[object]] = [] debtor_idx = 0 creditor_idx = 0 while debtor_idx < len(debtors) and creditor_idx < len(creditors): debtor_name, debt_left = debtors[debtor_idx] creditor_name, credit_left = creditors[creditor_idx] # Transfer as much as possible without making either side overshoot zero. payment_cents = min(debt_left, credit_left) payments.append([debtor_name, creditor_name, payment_cents]) debtors[debtor_idx][1] -= payment_cents creditors[creditor_idx][1] -= payment_cents # Use two separate `if` checks (not `elif`): when debt_left == credit_left, # both sides reach 0 on the same transfer and both pointers must advance. if debtors[debtor_idx][1] == 0: debtor_idx += 1 if creditors[creditor_idx][1] == 0: creditor_idx += 1 return payments def settle_optimally(balances: Dict[str, int]) -> List[List[object]]: """Return a valid settlement plan with the minimum possible number of transfers.""" # Phase 1: Extract only members with non-zero balances into parallel working lists. # names[i] has remaining signed balance amounts[i] (negative = owes, positive = owed). names: List[str] = [] amounts: List[int] = [] for name, balance in balances.items(): if balance != 0: names.append(name) amounts.append(balance) # Seed best_plan with the greedy solution so branch-and-bound has a tight upper bound. best_plan: List[List[object]] = settle(balances) # current_plan: stack of [payer, payee, cents] transfers chosen along the active search branch. current_plan: List[List[object]] = [] # Phase 2: Backtrack over who absorbs the entire balance of the first unsettled member. def search(start: int) -> None: nonlocal best_plan # Skip members whose balance was already cancelled out by an earlier transfer. while start < len(amounts) and amounts[start] == 0: start += 1 # Base case: everyone is at 0, so current_plan is a complete settlement. if start == len(amounts): if len(current_plan) < len(best_plan): best_plan = list(current_plan) return # Pruning: `start` still has a non-zero balance, so we need at least 1 more transfer. # If len(current_plan) + 1 cannot strictly beat best_plan, abandon this branch early. if len(current_plan) + 1 >= len(best_plan): return start_amount = amounts[start] for other in range(start + 1, len(amounts)): other_amount = amounts[other] # Only pair opposite signs (a debtor with a creditor); same-sign or zero transfers # never bring two balances closer to cancelling out. has_opposite_sign = (start_amount < 0 and other_amount > 0) or ( start_amount > 0 and other_amount < 0 ) if not has_opposite_sign: continue # Clear `start` in a single transfer by shifting its whole balance onto `other`. if start_amount < 0: current_plan.append([names[start], names[other], -start_amount]) else: current_plan.append([names[other], names[start], start_amount]) amounts[other] += start_amount amounts[start] = 0 search(start + 1) # Undo the transfer so the next loop iteration starts from a clean state. amounts[start] = start_amount amounts[other] = other_amount current_plan.pop() search(0) return best_plan✅ Submit now — all tests should pass.
Intuition & how it works
Imagine four friends finishing a weekend cabin trip with a stack of grocery, firewood, and kayak-rental receipts. Instead of making everyone reimburse everyone else receipt by receipt, imagine putting a hypothetical group pot in the middle of the table: each participant calculates a single net balance (one signed integer equal to total cents they paid for the group minus total cents of their own shares). Anyone with a negative balance owes money into the pot (a debtor), and anyone with a positive balance is owed money out of the pot (a creditor).
Why does a naive approach fall short? Keeping a pairwise matrix of who owes whom across n people can produce up to n * (n - 1) / 2 separate payments even when debts cancel in a circle (A owes B, B owes C, C owes A). Collapsing to net balances eliminates circular debts, and a greedy algorithm (making the locally simplest choice at each step — pairing the front debtor with the front creditor) settles everyone in at most n - 1 payments. However, greedy pairing still misses hidden exact matches that split the group into independent zero-sum subsets (smaller subgroups whose balances add up to zero on their own), whereas trying every possible transfer graph blindly without pruning explodes combinatorially.
Walk through Example 1 ({'Leo': 900, 'Nora': 300, 'Omar': -300, 'Zoe': -900}):
1. Greedy `settle` (pairs debtors [Omar 300, Zoe 900] with creditors [Leo 900, Nora 300] in order):
- Omar pays Leo 300 -> Omar is cleared (0), Leo still needs 600
- Zoe pays Leo 600 -> Leo is cleared (0), Zoe still owes 300
- Zoe pays Nora 300 -> Zoe and Nora both hit 0 --> 3 transfers total
2. Optimal `settle_optimally` (backtracking with branch-and-bound pruning):
- Branch 1: Omar (-300) absorbs Leo (+900) -> pruned once depth + 1 hits 3
- Branch 2: Zoe (-900) pays Leo (+900) -> both hit 0!
Omar (-300) pays Nora (+300) -> both hit 0! --> 2 transfers total
In settle_optimally, we use backtracking (recursively trying candidate choices and undoing them on return) combined with branch and bound (tracking the best complete answer seen so far — initialized to the greedy settle plan — and abandoning any partial search path as soon as it cannot beat that bound).
Complexity
Let m be the total number of participants in balances, and let n (n <= m) be the number of participants with non-zero balances (D debtors and C creditors, so n = D + C).
settletime:O(m). We scan allmdictionary entries once to builddebtorsandcreditors, and each iteration of thewhileloop zeroes out at least one debtor or creditor and advances its pointer, so the loop runs at mostD + C - 1 < mtimes withO(1)work per step.settlespace:O(m). Thedebtors,creditors, and outputpaymentslists each store at mostmentries.settle_optimallytime:O((n - 1)! * n)worst case (exponential inn). Finding the maximum number of zero-sum subsets is NP-hard (at least as hard as the subset-sum problem, which asks whether any subset of numbers adds up to zero, so no polynomial-time algorithm is known). At unsettled indexs, the loop tries at mostn - 1 - slater opposite-sign partners, creating at most(n - 1)!search leaves; branch-and-bound cuts off many branches early, easily handling groups of ~12 participants.settle_optimallyspace:O(m). Filtering non-zero balances takesO(n), the recursion call stack goes at mostnlevels deep, andcurrent_planplusbest_planeach hold at mostn - 1transfers.
Edge cases
- Empty input
{}or all zero balances{'Leo': 0, 'Nora': 0}: Bothdebtorsandcreditorsare empty, so both functions immediately return[]. - Participants with
0balance mixed with active participants (such as'Eli': 0in Example 2): Skipped during Phase 1, so someone who is already square never sends or receives a transfer. - Equal debtor and creditor mid-scan (
{'A': 10, 'B': -10, 'C': 5, 'D': -5}): Both pointers advance on the same iteration, avoiding a0-cent follow-up transfer. - Single debtor owing multiple creditors (or vice versa):
settleemits one transfer per creditor, which is also optimal because no smaller non-empty subset can sum to0. - Pass-through transfers in
settle_optimally: Becausesettle_optimallyshiftsstart's entire balance onto one opposite-sign partner, an intermediate participant may temporarily over-receive and forward the excess (for example, on{A: -4, B: -4, C: 1, D: 4, E: 3},ApaysC4andCpaysE3). If a product requires strictly debtor-to-creditor payments without pass-throughs, take each connected component (isolated subgroup of people linked by transfers) fromsettle_optimallyand runsettleinside each component — the transfer count stays minimal!
Common mistakes
- Representing money with floating-point numbers (
float): Binary floats cannot represent0.10exactly (0.1 + 0.2 != 0.3), causing balances to fail== 0checks by1e-16; always store integer minor units (cents). - Mutating the caller's
balancesdictionary: Previewing a settlement plan must be side-effect-free; modifyingbalancesin place corrupts the caller's state before any real payment occurs. - Using
elifinstead of twoifs when advancingdebtor_idxandcreditor_idx: Whendebt_left == credit_left,elifleaves one zeroed-out participant at the front and produces a0-cent transfer on the next iteration. - Sorting debtors and creditors inside
settle: Sorting changes the payment pairs away from the input-order baseline expected by sample tests, and largest-first greedy still fails to minimize transfers (for instance, on{4, -6, -8, -8, 3, 9, 6}largest-first uses6transfers, while{6, -6}plus{4, 3, 9, -8, -8}needs only5). - Forgetting to restore
amountsandcurrent_planafter recursion: In backtracking, mutating shared arrays without undoingamounts[start],amounts[other], andcurrent_plan.pop()leaks state into sibling branches.
Alternative approaches
- Bitmask dynamic programming (
O(n * 2^n)time,O(2^n)space): A bitmask represents a subset of thenpeople as ann-bit integer where bitiis1if personiis included. Precomputesubset_sum[mask]for every mask from1to2^n - 1, then computemax_groups[mask]— the largest number of zero-sum groupsmaskcan be partitioned into — by takingmax(max_groups[mask ^ (1 << i)])over set bitsi, plus1wheneversubset_sum[mask] == 0. Forn = 16..20,O(n * 2^n)is much faster and more predictable thanO((n - 1)!)factorial branching.
def min_transfer_count_bitmask(balances: Dict[str, int]) -> int:
values = [v for v in balances.values() if v != 0]
n = len(values)
if n == 0:
return 0
subset_sum = [0] * (1 << n)
max_groups = [0] * (1 << n)
for mask in range(1, 1 << n):
lowest_bit = mask & -mask
idx = lowest_bit.bit_length() - 1
subset_sum[mask] = subset_sum[mask ^ lowest_bit] + values[idx]
best_prev = 0
for i in range(n):
if mask & (1 << i):
best_prev = max(best_prev, max_groups[mask ^ (1 << i)])
max_groups[mask] = best_prev + (1 if subset_sum[mask] == 0 else 0)
return n - max_groups[(1 << n) - 1]
Follow-up questions
- How would your schema and settlement logic adapt if participants log bills in several different currencies that cannot be added directly? Key every ledger balance by
(group_id, member_id, currency)rather than(group_id, member_id), and store integer minor units appropriate to each currency (for example, cents for USD vs. whole yen for JPY). By default, runsettleorsettle_optimallyindependently per currency slice — since each bill was recorded in one currency, every currency slice sums to zero on its own. If the group opts to settle everything in a single home currency, convert each currency's net balances at a locked-in exchange rate and write an explicit FX-conversion entry into the append-only log (a history table where rows are only inserted, never overwritten) so rounding pennies and exchange rates stay auditable. - When a group grows to around 30 participants, exact exponential search becomes too slow—how would you keep near-optimal settlement fast at that scale? At
n = 30, both factorial backtracking and2^30bitmask DP exceed interactive latency budgets, so combine fast exact reductions with a bounded heuristic. First, greedily cancel all exact opposite pairs (+xand-x) inO(n)using a hash map — this never hurts optimality — and optionally cancel exact zero-sum triples (a + b + c == 0). On the remainingknon-zero balances, start with greedy pairing (which uses at mostk - 1transfers vs. a lower bound ofceil(k / 2), guaranteeing at worst a 2x approximation) and run branch-and-bound under a strict time budget (say 50 ms) to tightenbest_planbefore returning. - How would you model an auditable timeline of completed peer-to-peer payments without conflating it with current unpaid balances? Record executed payments in an immutable
Transfer(id, group_id, payer, payee, amount_cents, created_at, idempotency_key)table indexed on(group_id, payer, created_at)and(group_id, payee, created_at), where an idempotency key is a unique client-generated token preventing duplicate rows on network retries.get_historyreads directly fromTransfer(andExpense), whereasget_balancescombines logged expenses and completed transfers to derive what remains unpaid. Becausesettleandsettle_optimallyare read-only preview functions, suggested transfers never appear in payment history until money actually moves. - Suppose a participant has only completed half of a recommended settlement plan when someone logs a new shared bill—how should the system handle the remaining recommendations? Attach a monotonically increasing
ledger_versionto each group's state and return that version with every settlement preview. Any transfers already completed before the new bill are recorded normally viarecord_transferand remain completely valid, because each completed transfer simply shifts net balances closer to zero while preserving the zero-sum invariant. Once the new bill incrementsledger_version, clients mark any unexecuted steps from the older preview as stale and request a fresh settlement plan computed from the updated net balances.
Follow-up questions
- How would your schema and settlement logic adapt if participants log bills in several different currencies that cannot be added directly?
- When a group grows to around 30 participants, exact exponential search becomes too slow—how would you keep near-optimal settlement fast at that scale?
- How would you model an auditable timeline of completed peer-to-peer payments without conflating it with current unpaid balances?
- Suppose a participant has only completed half of a recommended settlement plan when someone logs a new shared bill—how should the system handle the remaining recommendations?
Similar questions
- Group Expense Ledger and Minimum-Transfer Debt Settlement
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager