KatInterview

Fewest Transfers to Clear Everyone's Net Balance

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingbitmask-dpgreedysubset-sum

Last 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

  1. 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.
  2. Many right answers. Several distinct transfer lists may all be minimal in length; any one of them is accepted.
  3. 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).
  4. 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.
  5. 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.