Group Expense Ledger and Minimum-Transfer Debt Settlement
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Design a group expense-tracking service and implement its debt-settlement engine. In a live interview, the problem spans two halves:
- System & API Design: Specify functional and non-functional requirements for recording shared bills among group participants, computing exact per-member balances in integer minor units (such as cents), serving read-only payout previews, and logging completed repayments with idempotency and auditability. Sketch the core storage entities (
User,Group,Expense,ExpenseShare,Payment) and REST/service endpoints. - Settlement Algorithms: Once historical bills and repayments are aggregated into each participant's net balance, implement
settlement_plans(net_positions)to return both a fast baseline payout schedule ("settle") and a minimum-transfer payout schedule ("settle_optimally").
def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]:
Rules & Output Contract
net_positionsmaps each participant's name (str) to an integer balance (int):- A positive value means the participant is owed that amount overall (creditor).
- A negative value means the participant owes that amount overall (debtor).
- A zero value means the participant is already even and must not appear in any transfer.
- Conservation check: If the values in
net_positionsdo not sum to0, raiseValueError. Do not mutatenet_positions. - Return a dictionary with two keys,
"settle"and"settle_optimally", each mapping to{"transactions": [[payer, payee, amount], ...], "count": int}:"settle"runs a single two-pointer sweep across all non-zero debtors and creditors in their appearance order innet_positions, transferringmin(remaining_debt, remaining_credit)at each step (producing at mostn - 1transfers fornnon-zero participants)."settle_optimally"clears every balance using the strictly minimum possible number of transfers (n - G, whereGis the maximum number of disjoint zero-sum subsets into which thennon-zero participants can be partitioned). Order non-zero participants to maximize zero-sum prefixes (breaking bitmask DP ties toward smaller participant indices), sort each resulting zero-sum group by input appearance order, and run the two-pointer sweep within each group.- In both plans, each transfer
[payer, payee, amount]hasamount > 0andpayer != payee, and"transactions"is sorted by(payer, payee)using the participants' appearance order innet_positions.
Examples
Example 1
Input: net_positions = {"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}
Output:
{
"settle": {
"transactions": [["Nora", "Maya", 15], ["Owen", "Maya", 20], ["Owen", "Leo", 15]],
"count": 3
},
"settle_optimally": {
"transactions": [["Nora", "Leo", 15], ["Owen", "Maya", 35]],
"count": 2
}
}
Walk-through: Pairing debtors [Nora: 15, Owen: 35] against creditors [Maya: 35, Leo: 15] front-to-back sends 15 from Nora to Maya, leaving Maya owed 20 and causing Owen to split payments across Maya (20) and Leo (15) for 3 transfers total. Partitioning into the two independent zero-sum pairs {Leo: +15, Nora: -15} and {Maya: +35, Owen: -35} settles everyone in 4 - 2 = 2 transfers.
Example 2
Input: net_positions = {"Eli": -25, "Zoe": 0, "Kai": 25}
Output:
{
"settle": {"transactions": [["Eli", "Kai", 25]], "count": 1},
"settle_optimally": {"transactions": [["Eli", "Kai", 25]], "count": 1}
}
Walk-through: Zoe already has a 0 balance and is excluded. Eli pays Kai 25 in 1 transfer under both strategies.
Example 3
Input: net_positions = {"Aria": -12, "Ben": -18, "Chloe": 30}
Output:
{
"settle": {"transactions": [["Aria", "Chloe", 12], ["Ben", "Chloe", 18]], "count": 2},
"settle_optimally": {"transactions": [["Aria", "Chloe", 12], ["Ben", "Chloe", 18]], "count": 2}
}
Walk-through: No proper non-empty subset sums to 0, so G = 1 and at least 3 - 1 = 2 transfers are required. Both Aria and Ben pay Chloe directly.
Example 4
Input: net_positions = {"Sam": 0, "Tara": 0, "Uma": 0}
Output:
{
"settle": {"transactions": [], "count": 0},
"settle_optimally": {"transactions": [], "count": 0}
}
Walk-through: Every participant is already settled, so zero transfers are needed.
Constraints
0 <= n <= 20, wherenis the number of participants with a non-zero balance innet_positions.- All balances are integers representing minor currency units (
-10^9 <= balance <= 10^9). - A valid input satisfies
sum(net_positions.values()) == 0; otherwisesettlement_plansmust raiseValueError. - Calling
settlement_plansmust leave the inputnet_positionsdictionary unchanged.
Step-by-step walkthrough
Understand the problem and output contract
This interview spans two halves: designing a group expense-tracking service and implementing its settlement engine
settlement_plans(net_positions).In the coding half, all historical bills and repayments have already been aggregated into
net_positions, a dictionary mapping each participant to an integer net balance in minor currency units (such as cents):- Positive (
+35): the group owes this participant 35 units overall (a creditor). - Negative (
-15): this participant owes the group 15 units overall (a debtor). - Zero (
0): this participant is already completely even. - Because every split share belongs to someone in the group, all net balances must sum to
0.
We must return a dictionary containing two valid payout schedules:
{ "settle": {"transactions": [[payer, payee, amount], ...], "count": k1}, "settle_optimally": {"transactions": [[payer, payee, amount], ...], "count": k2}, }settleclears everyone's balance quickly (using at mostn - 1transfers fornnon-zero participants).settle_optimallyclears everyone's balance using the strictly minimum possible number of transfers.- To produce a deterministic output order, we preserve the input dictionary's participant order when pairing debtors with creditors, and sort finished transfers by
(payer, payee)in that input order.
- Positive (
Design context: from raw bills to net balances
Before writing code, let's anchor the system and API half concisely so you can present a crisp design discussion in an interview:
Core tables (source of truth — all money stored as integer cents, never floats): User(id, name) Group(id, name) GroupMember(group_id, user_id) Expense(id, group_id, paid_by, amount_cents, currency, split_type, version, idempotency_key) ExpenseShare(expense_id, user_id, share_cents) -- exact cent shares summing to amount_cents Payment(id, group_id, payer, payee, amount_cents, idempotency_key) -- append-only real transfers Derived net balance for participant m: net(m) = sum(expenses m paid) - sum(m's ExpenseShares) + sum(payments m sent) - sum(payments m received) Core API endpoints: POST /groups/{g}/expenses -- create expense + shares (with idempotency_key) PUT /groups/{g}/expenses/{id} -- edit expense (with expected_version) GET /groups/{g}/balances -- returns {member: net_cents} GET /groups/{g}/settlement?optimal=true -- pure read preview; never mutates balances! POST /groups/{g}/payments -- record an actual repaymentFour non-functional rules protect real money:
- Integer minor units everywhere:
0.1 + 0.2 != 0.3in binary floating point; storing integer cents and assigning remainder cents deterministically (e.g.,1000cents split 3 ways ->334, 333, 333cents) keeps the group sum at0. - Source of truth vs. derived state: Bills, split shares, and repayments are immutable/versioned facts; balances are derived from them so editing a bill never corrupts history.
- Idempotent writes and optimistic locking: An idempotency key (a unique client-generated ID per request) prevents network retries from double-recording a write, and
expected_version(optimistic concurrency control) prevents two simultaneous edits from silently overwriting each other. - Preview vs. recorded repayment: Requesting a payout schedule is a read-only suggestion; balances change only when a
Paymentrecord is written. Out of scope: direct bank rails, cross-currency FX brokerage, and authentication.
- Integer minor units everywhere:
Fast baseline (`settle`): two-pointer sweep across debtors and creditors
Do payout transfers have to replay every grocery or fuel receipt backward? No! Money is fungible: as long as every debtor sends their exact negative balance and every creditor receives their exact positive balance, everyone ends at
0.That gives a fast, clean two-pointer sweep for
_greedy_payments:- Collect all debtors (
amount < 0, storing+abs(amount)left to pay) and all creditors (amount > 0, storingamountleft to receive). - Point
debtor_ptrat the first debtor andcreditor_ptrat the first creditor. - Transfer
min(still_owes, still_owed)from that debtor to that creditor. - Subtract
transferfrom both, and advance whichever pointer (or both!) hits0.
Example: debtors = [[Nora, 15], [Owen, 35]], creditors = [[Maya, 35], [Leo, 15]] Step 1: Nora owes 15, Maya is owed 35 -> Nora pays Maya 15 (Nora hits 0 -> advance debtor_ptr; Maya has 20 left) Step 2: Owen owes 35, Maya is owed 20 -> Owen pays Maya 20 (Maya hits 0 -> advance creditor_ptr; Owen has 15 left) Step 3: Owen owes 15, Leo is owed 15 -> Owen pays Leo 15 (BOTH hit 0 -> advance both; done!)Why does this take at most
k - 1transfers forknon-zero participants? Every transfer reduces at least one person's remaining balance to0, and because total debt equals total credit, the final transfer always clears two people simultaneously.def _greedy_payments(amounts: List[int], members: List[int]) -> List[Tuple[int, int, int]]: """Settle `members` (indices into `amounts`, whose balances sum to zero) using two pointers. Returns (payer_idx, payee_idx, amount_cents) triples in at most len(members) - 1 payments. """ # debtors: list of [member_idx, cents_still_to_pay], e.g. [[2, 15], [3, 35]] debtors: List[List[int]] = [] # creditors: list of [member_idx, cents_still_to_receive], e.g. [[0, 35], [1, 15]] creditors: List[List[int]] = [] for member_idx in members: if amounts[member_idx] < 0: debtors.append([member_idx, -amounts[member_idx]]) elif amounts[member_idx] > 0: creditors.append([member_idx, amounts[member_idx]]) payments: List[Tuple[int, int, int]] = [] debtor_ptr = 0 creditor_ptr = 0 # Pair the current debtor and current creditor until both lists run out together. while debtor_ptr < len(debtors) and creditor_ptr < len(creditors): payer_idx, still_owes = debtors[debtor_ptr] payee_idx, still_owed = creditors[creditor_ptr] # Transfer whichever side needs less so nobody ever overshoots zero. transfer = min(still_owes, still_owed) payments.append((payer_idx, payee_idx, transfer)) debtors[debtor_ptr][1] -= transfer creditors[creditor_ptr][1] -= transfer # Advance BOTH pointers if a tie cleared both sides at once (avoids 0-cent payments). if debtors[debtor_ptr][1] == 0: debtor_ptr += 1 if creditors[creditor_ptr][1] == 0: creditor_ptr += 1 return payments def _format_plan(payments: List[Tuple[int, int, int]], names: List[str]) -> Dict[str, object]: """Convert index triples to [payer_name, payee_name, amount] sorted by payer then payee.""" transactions: List[List[object]] = [] for payer_idx, payee_idx, amount in sorted(payments): transactions.append([names[payer_idx], names[payee_idx], amount]) return {"transactions": transactions, "count": len(transactions)}- Collect all debtors (
Exact minimum (`settle_optimally`): why the minimum is `n - G`
Look at why the sweep needed 3 transfers on
{"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}when 2 were enough:Nora (-15)paidMaya (+35)first, entangling{Maya, Owen}with{Leo, Nora}! Had we kept{Maya: +35, Owen: -35}and{Leo: +15, Nora: -15}as two separate zero-sum groups, each group of 2 would have settled in2 - 1 = 1transfer (2total).Let's prove that for
nnon-zero participants, the minimum number of transfers is alwaysn - G, whereGis the maximum number of disjoint zero-sum subsets thenparticipants can be partitioned into:Greedy sweep (1 group of 4 -> 4 - 1 = 3 edges) Optimal split (2 groups of 2 -> 4 - 2 = 2 edges) Nora(-15) ----15----> Maya(+35) Nora(-15) ----15----> Leo(+15) ^ | 20 Owen(-35) ----35----> Maya(+35) Owen(-35) ----15----> Leo(+15)- No plan can beat
n - G(lower bound): Draw thennon-zero participants as dots and each transfer in any valid plan as a line between two dots. Look at the connected components (isolated islands of dots linked by transfers). Because no money crosses between different islands and everyone ends at0, the starting balances inside each island must already add up to0! If there arecislands of sizess_1, ..., s_c, connectings_idots takes at leasts_i - 1lines, so total transfers>= (s_1 - 1) + ... + (s_c - 1) = n - c. Sinceccannot exceed the maximum possible number of zero-sum subsetsG, every valid plan uses at leastn - Gtransfers. - We can always achieve
n - G(upper bound): Partition thenparticipants intoGzero-sum groups and run_greedy_paymentsinside each group. Each groupiuses at mosts_i - 1transfers, summing to at mostn - G(and therefore exactlyn - G)!
Notice that testing whether
G >= 2("does any non-empty proper subset sum to zero?") is the classic subset-sum problem (which is NP-complete, meaning no known polynomial-time algorithm solves all cases). That tells us anO(n * 2^n)exact algorithm is the right tool for typical groups up to ~20 participants.- No plan can beat
Finding `G` with bitmask dynamic programming
How do we find the best partition into zero-sum subsets in
O(n * 2^n)time?Imagine lining up the
nparticipants in some left-to-right order and counting how many prefixes (first1person, first2people, ..., allnpeople) sum to0:Order: [ Nora(-15), Leo(+15), Owen(-35), Maya(+35) ] Prefix sum: -15 0 -35 0 ^ ^ cut here! cut here! -> 2 zero-sum groups: {Leo, Nora} and {Maya, Owen}Whenever a prefix sums to
0, the slice since the previous0prefix also sums to0(0 - 0 = 0)! Conversely, concatenatingGzero-sum groups side by side creates an ordering with at leastGzero-sum prefixes. So maximizing zero-sum groups is identical to finding a participant ordering with the most zero-sum prefixes.To search over subsets instead of all
n!permutations, we represent each subset of{0, ..., n - 1}as a bitmask — an integer from0to2^n - 1whosei-th binary bit (1 << i) is1if participantiis in the subset and0if not:n = 4 (bit 0=Maya, bit 1=Leo, bit 2=Nora, bit 3=Owen): mask = 6 (binary 0110) -> subset {Leo, Nora}, subset_sum[6] = +15 + (-15) = 0 mask = 15 (binary 1111) -> subset {Maya,Leo,Nora,Owen}, subset_sum[15] = 0For each non-empty
mask, if participantiis placed last amongmask's members, the earlier prefixes come fromprev_mask = mask ^ (1 << i)(maskwith bititurned off), plus1extra zero-sum prefix ifsubset_sum[mask] == 0:best_groups[mask] = max over (i in mask) of best_groups[mask ^ (1 << i)] + (1 if subset_sum[mask] == 0 else 0)Remembering which
iwon inlast_member[mask]lets us walk backward fromfull_maskto0to recover the exact optimal ordering, then cut whenever the running sum hits0.Code `_max_zero_sum_groups` and `settlement_plans`
Notice how we also build
subset_sumcleanly without cryptic bit tricks: adding participantmember_idx(member_bit = 1 << member_idx) to every already-computedprev_mask < member_bitfills all2^nsubset sums inO(2^n)additions.def _max_zero_sum_groups(amounts: List[int]) -> List[List[int]]: """Partition `0 .. len(amounts) - 1` into the maximum number of disjoint zero-sum subsets.""" n = len(amounts) if n == 0: return [] num_masks = 1 << n full_mask = num_masks - 1 # Phase 1: Precompute subset_sum[mask] = sum of balances for members whose bit is 1 in `mask`. subset_sum = [0] * num_masks for member_idx in range(n): member_bit = 1 << member_idx for prev_mask in range(member_bit): subset_sum[prev_mask | member_bit] = subset_sum[prev_mask] + amounts[member_idx] # Phase 2: Bitmask DP over subset orderings. # best_groups[mask] = maximum number of zero-sum prefixes achievable by ordering `mask`. # last_member[mask] = which member sits at the end of `mask` in that best ordering. best_groups = [0] * num_masks last_member = [-1] * num_masks for mask in range(1, num_masks): best_prev = -1 chosen_member = -1 for member_idx in range(n): member_bit = 1 << member_idx if mask & member_bit: prev_mask = mask ^ member_bit if best_groups[prev_mask] > best_prev: best_prev = best_groups[prev_mask] chosen_member = member_idx # If `mask` itself sums to zero, completing `mask` finishes one more zero-sum group. if subset_sum[mask] == 0: best_groups[mask] = best_prev + 1 else: best_groups[mask] = best_prev last_member[mask] = chosen_member # Phase 3: Reconstruct the member ordering from full_mask back to 0, then reverse it. order: List[int] = [] mask = full_mask while mask > 0: member_idx = last_member[mask] order.append(member_idx) mask ^= 1 << member_idx order.reverse() # Phase 4: Cut `order` every time the running prefix sum hits zero. # Because previous groups summed to 0, each cut slice also sums to 0 on its own. groups: List[List[int]] = [] current_group: List[int] = [] running_sum = 0 for member_idx in order: current_group.append(member_idx) running_sum += amounts[member_idx] if running_sum == 0: # Sort indices so _greedy_payments processes members in original input order. groups.append(sorted(current_group)) current_group = [] return groupsFinally,
settlement_plansfilters out0-balance participants, validatessum(amounts) == 0, runs_greedy_paymentsonce on everyone forsettle, and runs_greedy_paymentson each zero-sum group forsettle_optimally— never mutating the caller'snet_positionsdictionary.def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]: # Filter out settled members (balance == 0) while preserving input order for tie-breaking. names: List[str] = [] amounts: List[int] = [] for name, amount in net_positions.items(): if amount != 0: names.append(name) amounts.append(amount) # Conservation of money: every cent owed by someone must be owed to someone else. if sum(amounts) != 0: raise ValueError("net positions must sum to zero") # Plan 1 (settle): single greedy sweep across all non-zero members (at most n - 1 payments). all_members = list(range(len(names))) simple_payments = _greedy_payments(amounts, all_members) # Plan 2 (settle_optimally): partition into G zero-sum groups and sweep each (n - G payments). optimal_payments: List[Tuple[int, int, int]] = [] for group in _max_zero_sum_groups(amounts): optimal_payments.extend(_greedy_payments(amounts, group)) return { "settle": _format_plan(simple_payments, names), "settle_optimally": _format_plan(optimal_payments, names), }Walk through Example 1 end to end
Input:
{"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}->names = ["Maya", "Leo", "Nora", "Owen"],amounts = [35, 15, -15, -35].1. settle (all_members = [0, 1, 2, 3]): debtors = [[2(Nora), 15], [3(Owen), 35]], creditors = [[0(Maya), 35], [1(Leo), 15]] - Nora pays Maya 15 -> Nora=0 (next debtor), Maya=20 - Owen pays Maya 20 -> Owen=15, Maya=0 (next creditor) - Owen pays Leo 15 -> Owen=0, Leo=0 (done) Result: [["Nora", "Maya", 15], ["Owen", "Maya", 20], ["Owen", "Leo", 15]], count = 3 2. settle_optimally: Zero-sum masks: mask 6 ({Leo, Nora}), mask 9 ({Maya, Owen}), mask 15 ({Maya, Leo, Nora, Owen}) best_groups[15] = 2 -> groups = [[1, 2], [0, 3]] ({Leo, Nora} and {Maya, Owen}) - Sweep {Leo, Nora}: Nora pays Leo 15 - Sweep {Maya, Owen}: Owen pays Maya 35 Sorted by (payer_idx, payee_idx): [["Nora", "Leo", 15], ["Owen", "Maya", 35]], count = 4 - 2 = 2Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def _greedy_payments(amounts: List[int], members: List[int]) -> List[Tuple[int, int, int]]: """Settle `members` (indices into `amounts`, whose balances sum to zero) using two pointers. Returns (payer_idx, payee_idx, amount_cents) triples in at most len(members) - 1 payments. """ # debtors: list of [member_idx, cents_still_to_pay], e.g. [[2, 15], [3, 35]] debtors: List[List[int]] = [] # creditors: list of [member_idx, cents_still_to_receive], e.g. [[0, 35], [1, 15]] creditors: List[List[int]] = [] for member_idx in members: if amounts[member_idx] < 0: debtors.append([member_idx, -amounts[member_idx]]) elif amounts[member_idx] > 0: creditors.append([member_idx, amounts[member_idx]]) payments: List[Tuple[int, int, int]] = [] debtor_ptr = 0 creditor_ptr = 0 # Pair the current debtor and current creditor until both lists run out together. while debtor_ptr < len(debtors) and creditor_ptr < len(creditors): payer_idx, still_owes = debtors[debtor_ptr] payee_idx, still_owed = creditors[creditor_ptr] # Transfer whichever side needs less so nobody ever overshoots zero. transfer = min(still_owes, still_owed) payments.append((payer_idx, payee_idx, transfer)) debtors[debtor_ptr][1] -= transfer creditors[creditor_ptr][1] -= transfer # Advance BOTH pointers if a tie cleared both sides at once (avoids 0-cent payments). if debtors[debtor_ptr][1] == 0: debtor_ptr += 1 if creditors[creditor_ptr][1] == 0: creditor_ptr += 1 return payments def _max_zero_sum_groups(amounts: List[int]) -> List[List[int]]: """Partition `0 .. len(amounts) - 1` into the maximum number of disjoint zero-sum subsets.""" n = len(amounts) if n == 0: return [] num_masks = 1 << n full_mask = num_masks - 1 # Phase 1: Precompute subset_sum[mask] = sum of balances for members whose bit is 1 in `mask`. subset_sum = [0] * num_masks for member_idx in range(n): member_bit = 1 << member_idx for prev_mask in range(member_bit): subset_sum[prev_mask | member_bit] = subset_sum[prev_mask] + amounts[member_idx] # Phase 2: Bitmask DP over subset orderings. # best_groups[mask] = maximum number of zero-sum prefixes achievable by ordering `mask`. # last_member[mask] = which member sits at the end of `mask` in that best ordering. best_groups = [0] * num_masks last_member = [-1] * num_masks for mask in range(1, num_masks): best_prev = -1 chosen_member = -1 for member_idx in range(n): member_bit = 1 << member_idx if mask & member_bit: prev_mask = mask ^ member_bit if best_groups[prev_mask] > best_prev: best_prev = best_groups[prev_mask] chosen_member = member_idx # If `mask` itself sums to zero, completing `mask` finishes one more zero-sum group. if subset_sum[mask] == 0: best_groups[mask] = best_prev + 1 else: best_groups[mask] = best_prev last_member[mask] = chosen_member # Phase 3: Reconstruct the member ordering from full_mask back to 0, then reverse it. order: List[int] = [] mask = full_mask while mask > 0: member_idx = last_member[mask] order.append(member_idx) mask ^= 1 << member_idx order.reverse() # Phase 4: Cut `order` every time the running prefix sum hits zero. # Because previous groups summed to 0, each cut slice also sums to 0 on its own. groups: List[List[int]] = [] current_group: List[int] = [] running_sum = 0 for member_idx in order: current_group.append(member_idx) running_sum += amounts[member_idx] if running_sum == 0: # Sort indices so _greedy_payments processes members in original input order. groups.append(sorted(current_group)) current_group = [] return groups def _format_plan(payments: List[Tuple[int, int, int]], names: List[str]) -> Dict[str, object]: """Convert index triples to [payer_name, payee_name, amount] sorted by payer then payee.""" transactions: List[List[object]] = [] for payer_idx, payee_idx, amount in sorted(payments): transactions.append([names[payer_idx], names[payee_idx], amount]) return {"transactions": transactions, "count": len(transactions)} def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]: # Filter out settled members (balance == 0) while preserving input order for tie-breaking. names: List[str] = [] amounts: List[int] = [] for name, amount in net_positions.items(): if amount != 0: names.append(name) amounts.append(amount) # Conservation of money: every cent owed by someone must be owed to someone else. if sum(amounts) != 0: raise ValueError("net positions must sum to zero") # Plan 1 (settle): single greedy sweep across all non-zero members (at most n - 1 payments). all_members = list(range(len(names))) simple_payments = _greedy_payments(amounts, all_members) # Plan 2 (settle_optimally): partition into G zero-sum groups and sweep each (n - G payments). optimal_payments: List[Tuple[int, int, int]] = [] for group in _max_zero_sum_groups(amounts): optimal_payments.extend(_greedy_payments(amounts, group)) return { "settle": _format_plan(simple_payments, names), "settle_optimally": _format_plan(optimal_payments, names), }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine four teammates reconciling shared cabin, grocery, and fuel bills at the end of a trip. Rather than reimbursing every individual receipt one by one, each person writes a single integer on an index card: their net balance (total cents owed to them if positive, or owed by them overall if negative — all cards always add up to 0). Once we work with net balances, any debtor can pay any creditor. For settle, we line up debtors on the left and creditors on the right and pair them front-to-back in at most n - 1 transfers. For settle_optimally, we notice that every independent mini-cluster whose cards already cancel out to 0 saves one whole transfer: partitioning n non-zero people into G disjoint zero-sum subsets lets us clear everyone in n - G transfers — and viewing transfers as graph edges proves no valid plan can ever do fewer, because every connected component (isolated cluster of people linked by transfers) must sum to 0 and needs at least size - 1 edges!
Why do simpler shortcuts fail to find the minimum? Reimbursing pairwise-netted IOUs can take O(n^2) transfers, and greedy heuristics — even "largest debtor pays largest creditor" — can shatter clean zero-sum subsets (for instance, on {-4, +3, +2, -3, +2}, matching -4 with +3 breaks {+3, -3} and {-4, +2, +2}, taking 4 transfers instead of 3). Meanwhile, brute-forcing all (n - 1)! pairings explodes factorially, whereas bitmask dynamic programming (representing each subset of n participants as an n-bit integer and building answers from smaller subsets to larger ones) finds the exact maximum G in O(n * 2^n) time.
Here is how both methods run on Example 1 ({"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}, with n = 4 non-zero participants):
1. Fast sweep (settle):
Debtors: [Nora: 15, Owen: 35] Creditors: [Maya: 35, Leo: 15]
- Nora pays Maya 15 (Nora cleared; Maya still owed 20)
- Owen pays Maya 20 (Maya cleared; Owen still owes 15)
- Owen pays Leo 15 (Owen and Leo both cleared)
-> 3 transfers: [Nora -> Maya: 15], [Owen -> Maya: 20], [Owen -> Leo: 15]
2. Optimal partition (settle_optimally):
Split into G = 2 zero-sum subsets: {Leo: +15, Nora: -15} and {Maya: +35, Owen: -35}
- Inside {Leo, Nora}: Nora pays Leo 15 (2 - 1 = 1 transfer)
- Inside {Maya, Owen}: Owen pays Maya 35 (2 - 1 = 1 transfer)
-> n - G = 4 - 2 = 2 transfers: [Nora -> Leo: 15], [Owen -> Maya: 35]
Complexity
Let m be the total number of entries in net_positions and n (n <= m) be the number of participants with a non-zero balance.
settletime:O(m + n log n). We scanmentries once inO(m)to drop zeros, run the two-pointer sweep where every step clears at least one debtor or creditor in at mostn - 1iterations (O(n)), and sort at mostn - 1output triples inO(n log n).settlespace:O(n). We store only the debtor/creditor lists and at mostn - 1output transfers.settle_optimallytime:O(m + n * 2^n). Precomputingsubset_sumacross all2^nbitmasks takesO(2^n)additions; fillingbest_groupschecksnparticipant bits for each of the2^nmasks inO(n * 2^n)operations; reconstructing the ordering, cutting groups, sweeping each group, and sorting the output takeO(n log n). In Python,n <= 18finishes in a fraction of a second andn = 20takes roughly one second.settle_optimallyspace:O(2^n). The three arrayssubset_sum,best_groups, andlast_membereach store2^nintegers (about 1 million ints each atn = 20).
Edge cases
- Empty group (
{}) or everyone already at0({"Sam": 0, "Tara": 0, "Uma": 0}): Filtering leavesn = 0non-zero participants, and both plans cleanly return{"transactions": [], "count": 0}. - Mix of zero and non-zero participants (
{"Eli": -25, "Zoe": 0, "Kai": 25}): Zero-balance participants are dropped up front, since routing money through someone at0would only add wasted transfers. - Single creditor and multiple debtors (
{"Aria": -12, "Ben": -18, "Chloe": 30}): No proper non-empty subset sums to0, soG = 1and bothsettleandsettle_optimallyrequire3 - 1 = 2transfers. - Zero-sum triples with no opposite pairs (e.g.,
{+1, +2, -3, +4, +5, -9}): Even though no+x / -xpair exists, the bitmask DP discovers{+1, +2, -3}and{+4, +5, -9}(G = 2,6 - 2 = 4transfers vs.5in a plain sweep). - Corrupted ledger (
sum(amounts) != 0): RaisesValueErrorimmediately instead of looping infinitely or leaving unpaid remainders.
Common mistakes
- Using floating-point numbers (
float) for currency: Binary floats suffer from rounding errors like0.1 + 0.2 == 0.30000000000000004, which breaks exact zero-sum checks (subset_sum[mask] == 0); always represent money in integer minor units (cents). - Using
elifwhen advancingdebtor_ptrandcreditor_ptr: When a debtor owes15and a creditor is owed15, one transfer clears both to0. Usingelifleaves one pointer sitting on a0balance and emits bogus0-cent transfers on the next step. - Mutating the caller's
net_positionsdictionary in place: Viewing a payout plan is a read-only preview; altering the input dictionary silently wipes out balances before anyone actually sends money. - Assuming "largest debtor pays largest creditor" is optimal: Greedy matching by size fails whenever splitting a large balance across two smaller ones unlocks extra zero-sum groups (as on
{-4, +3, +2, -3, +2}). - Greedily peeling off small zero-sum triples first: Pairing off exact opposites (
+xand-x) is always safe, because swapping elements shows an optimal partition can always keep{+x, -x}together. However, greedily removing a zero-sum triple can hurt: on{+1, +2, -3, +3, -1, -2}, grabbing{+1, +2, -3}leaves{+3, -1, -2}(2groups,4transfers) instead of the three pairs{+1, -1},{+2, -2},{+3, -3}(3groups,3transfers)!
Alternative approaches
- Backtracking DFS over remaining balances: Pick the first non-zero participant
iand try settlingi's entire balance against each opposite-sign participantj(amounts[j] += amounts[i]), recursing with branch-and-bound pruning. While fast on tiny inputs, its worst-case branching factor grows like(n - 1)!, whereas bitmask DP guaranteesO(n * 2^n)time. - Submask enumeration DP (
O(3^n)): Computedp[mask] = 1 + max(dp[sub] + dp[mask ^ sub])by iterating over submasks of each zero-sum mask. It expresses the partition directly, but visiting all(mask, submask)pairs takes3^nsteps (~3.5 billion atn = 20) compared ton * 2^n(~20 million atn = 20) for our prefix-ordering DP.
Follow-up questions
- How would you handle groups of 40 or 50 participants where exact subset-sum partitioning becomes too slow? Because testing whether
G >= 2is the NP-complete subset-sum problem (no known algorithm runs in polynomial time on every large input), use a layered pipeline. First, greedily cancel all exact opposite pairs+xand-xinO(n)time using a hash map — that reduction is mathematically lossless and often shrinks real groups dramatically. If the remainingn'non-zero participants satisfyn' <= 20, run the exactO(n' * 2^n')bitmask DP; otherwise, fall back to theO(n')two-pointer sweep (which uses at mostn' - 1transfers — guaranteed to be under2xthe theoretical optimum, since every zero-sum subset has at least2people so the optimum is at leastn' / 2) or run a time-boxed integer linear programming (ILP) / heuristic search. - Suppose a participant modifies a past bill after teammates have already viewed a suggested payout plan. Which records update and which stay untouched? Modifying a bill writes a new version of its
ExpenseandExpenseSharerows (preserving the prior version in an audit log), recomputes derived group balances, and invalidates any cached or displayed payout preview so clients fetch a fresh schedule. What must remain untouched: already-recordedPaymentrows represent real money that moved outside the service and stay immutable, the group's net balances must still sum to0, retries carrying the same idempotency key (unique client request token) must not apply the edit twice, and optimistic concurrency control (expected_version) must reject stale concurrent edits instead of silently overwriting a teammate's update. - What changes algorithmically if transfers are restricted to pairs who already had a direct debt between them? Now repayments may only flow along existing directed edges of the pairwise debt graph rather than between arbitrary debtors and creditors, so the
n - Gformula no longer holds (a zero-sum subset might lack direct debt edges among its members). A clean safe simplification is cycle cancelling (finding a directed loop likeU -> V -> W -> Uwhere each person owes the next, and subtracting the smallest debt on the loop from every edge in the loop): each cancelled cycle deletes at least one debt edge without altering anyone's net balance or introducing strangers. Once all cycles are eliminated, paying the remaining edges is valid, though minimizing active edges under per-edge capacity limits requires a combinatorial search or mixed-integer solver. - How should the data model and settlement logic adapt when bills are logged in multiple currencies? Never sum raw integers across currencies; store an explicit ISO
currencycode on every bill and repayment and track independent net balances per(member_id, currency)pair, where each currency's balances sum to0in that currency's minor unit (noting that USD/EUR use 2 decimal places, JPY uses 0, and KWD uses 3). By default, settle each currency independently so nobody bears exchange-rate drift. If the group opts into single-currency settlement, lock and persist an explicit exchange-rate snapshot at preview/confirmation time, convert balances into the target currency's integer minor units, and assign any 1-unit rounding remainder deterministically so converted balances still sum to0.
Follow-up questions
- How would you handle groups of 40 or 50 participants where exact subset-sum partitioning becomes too slow?
- Suppose a participant modifies a past bill after teammates have already viewed a suggested payout plan. Which records update and which stay untouched?
- What changes algorithmically if transfers are restricted to pairs who already had a direct debt between them?
- How should the data model and settlement logic adapt when bills are logged in multiple currencies?
Similar questions
- Group Expense Ledger and Minimum-Transfer 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