← Pinterest Interview Insights
My first instinct was to just compute net balances and greedily match the biggest debtor to the biggest creditor using a max-heap.
First, compute each person's net balance by summing all payments made and received. Then, use a greedy algorithm to match the largest debtor with the largest creditor, settling as much as possible in each transfer, until all balances are zero. This minimizes the number of transfers.
Pro tip: Mention that while the greedy approach is optimal for minimizing the number of transfers, it may not be unique; also, consider edge cases like multiple people per payment and floating-point precision.
Iterate through the list of payments, and for each payment, subtract the amount from the payer's balance and add an equal share to each beneficiary's balance. This yields each person's net balance.
Create two lists: one for people with negative balances (debtors) and one for people with positive balances (creditors). Ignore those with zero balance.
While both lists are non-empty, take the largest debtor and largest creditor, and transfer the minimum of their absolute balances. Update their balances and remove any that become zero.
Record each transfer as a tuple (debtor, creditor, amount) and return the list of transfers.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.