Fewest Transfers to Clear Everyone's Net Balance
Dynamic ProgrammingModel answerLast updated
Given payer/payee/amount triples, compute net balances and return an optimal (minimum-count) set of settlement transfers that zeroes everyone out.
You are given a collection of IOUs among a group of people, each written as a triple (payer, payee, amount) where amount is a positive integer. Produce a list of settlement transfers (from, to, amount) such that after applying every transfer, every person's net position is exactly zero, and the number of transfers is as small as possible. If more than one minimal list exists, return any of them.
What you must do
- Collapse first. Start by turning the raw IOUs into a single net figure per person: money they owe minus money owed to them. Anyone whose net figure is zero is already square and should be dropped from further work. Then plan transfers using only these net figures.
- Many right answers. Several distinct transfer lists may all be minimal in length; any one of them is accepted.
- Size assumptions. Amounts are integers. The basic version has at most ~20 people with a nonzero net figure. Also explain how your approach degrades as the number of such people grows, and how it copes when the IOU list is large or lopsided (one person on one side of very many IOUs).
- Big numbers. Consolidated net figures can be much larger than any single IOU; say how you keep them from overflowing (e.g. 64-bit counters) and note the invariant that the signed net figures must sum to zero.
- Method, justification, cost. Describe your algorithm (a lower bound via grouping, a pruned search on net figures, or a subset/partition formulation), argue why it is optimal, and give time and space complexity.
Example. IOUs: (A,B,10), (B,C,10). Net figures: A=+10, B=0, C=-10. One minimal answer: (A,C,10) — a single transfer instead of replaying the two IOUs.
Hints
Hint 1
Only net balances matter — an IOU chain whose intermediate people net to zero disappears entirely.
Hint 2
A set of k nonzero balances summing to zero can always be settled with exactly k−1 transfers, so minimizing transfers is the same as splitting the balances into as many zero-sum groups as possible.
Hint 3
Deciding the largest number of zero-sum groups is essentially partition/subset-sum, i.e. exponential in the number of people; a bitmask DP over subsets is the natural exact tool for n up to ~20.
Hint 4
Anyone whose net is zero, and any pair with exactly opposite balances, costs you nothing and can be peeled off first.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer starts by discarding the raw IOUs. They are noise. What matters is each person's net position.
Step 1 — Consolidate. Walk the IOU list once. For (u, v, a) add +a to bal[u] and −a to bal[v] (positive = net payer, negative = net receiver). Drop zero entries. Let n be how many people remain with a nonzero figure, and vals[0..n−1] their values. Two facts to state out loud: the signed values sum to exactly zero (each IOU contributes +a and −a), so a nonzero total means corrupt input — assert it; and consolidated values can reach E × maxAmount for E IOUs, so accumulate in 64-bit (or BigInteger/__int128, or Python ints which are unbounded).
Step 2 — The key reframing. Suppose the n nonzero people can be partitioned into g disjoint groups, each summing to zero. A zero-sum group of size k can always be settled in k − 1 transfers: repeatedly pair a payer with a receiver and move min(owed, owedTo); each transfer zeroes at least one person, and since the group sums to zero the last one zeroes two. So g groups cost n − g transfers. Maximizing g minimizes transfers, and the answer is n − g_max.
Step 3 — Computing g_max. This is where the problem turns NP-hard (deciding g ≥ 2 is partition), so exact answers are exponential. For n ≤ ~20 a bitmask DP is the clean tool:
ssum[mask]= sum of values in the subset, computed incrementally from the lowest set bit:ssum[m] = ssum[m ^ low] + vals[idx(low)].O(2^n).dp[mask]= the maximum number of zero-sum prefixes over all orderings of the people inmask. Transition: pick which person was added last —dp[m] = max_{i∈m} dp[m \ {i}] + [ssum[m] == 0]. Each zero-sum prefix ends one group.g_max = dp[full].O(n·2^n)time,O(2^n)space.
Step 4 — Reconstruct. Trace back from the full mask, at each step choosing any i with dp[m ^ {i}] == dp[m] − [ssum[m] == 0], collecting the chosen indices, then reverse to get an addition order. Sweep the order accumulating values; every time the running sum hits zero, close a group. That yields exactly g_max groups.
Step 5 — Settle each group. For a group C, build a payer list (positive balances) and a receiver list (negatives), then repeatedly move min(payerRemaining, receiverRemaining) from the front payer to the front receiver, advancing whichever hits zero. That is at most |C| − 1 transfers, O(n^2) overall.
Why this is optimal. Lower bound: view any valid transfer list as an undirected graph on the n people. Money only moves along edges, so the balance sum of each connected component must be zero — otherwise someone in it is left unsettled. A component on k vertices needs at least k − 1 edges, so with c components you use at least n − c transfers. Those components are disjoint zero-sum groups, so c ≤ g_max and any solution uses at least n − g_max. Upper bound: the construction above achieves exactly n − g_max. Bounds meet, so it is minimal. The DP's correctness is a standard argument: a partition into g zero-sum groups induces an ordering with g zero-sum prefixes and vice versa, and the DP maximizes over all orderings by choosing the last element.
Complexity. Consolidation O(E); subset sums O(2^n); DP O(n·2^n) time, O(2^n) memory (two int arrays of 2^20 ≈ 1M entries — about 20M transitions at n = 20, comfortably a few seconds in Java or C++); reconstruction and settlement O(n^2). Note n counts only nonzero-net people, often far fewer than the participant count.
Scaling, lopsided graphs, and overflow. Beyond ~20–25 nonzero people, the exact DP is out of reach. Fall back to heuristics in this order: cancel exact opposite pairs (+x with −x) since each is a guaranteed size-2 group; find zero-sum triples with a hash map; then run the greedy settlement on the rest, which guarantees at most n − 1 transfers. A hub who is on one side of many IOUs never hurts — the DP only sees net figures, and the greedy step naturally routes everything through the hub in about n − 1 transfers; graph size E only affects the linear consolidation. Keep balances in 64-bit, assert sum(bal) == 0, and note self-IOUs (a, a, x) cancel automatically.
Edge cases. No IOUs, or everyone netting to zero → return []. Cyclic equal IOUs (A→B→C→A) net to zero → zero transfers. One payer with many receivers → exactly n − 1.
A reference implementation: consolidate as above, build ssum and dp over 2^n masks, trace back an ordering, cut it at zero-sum prefixes, and greedily settle each group — returning the concatenated transfers.
Common mistakes. Trying to cancel IOUs pairwise on the raw list instead of on net figures (misses the A→B→C→A collapse). Forgetting that n excludes zero-net people, which inflates the DP. Assuming greedy always gives the optimum — it gives at most n − 1, which is often one or two more than the true minimum when the balances contain small zero-sum groups. And skipping the zero-sum assertion, which silently masks corrupt input.