← Pinterest Interview InsightsSoftware Engineer
The 'any valid solution' part is what saves you here, no need to minimize transactions.
First, compute each user's net balance by summing all amounts they paid and subtracting all amounts they received. Then, repeatedly match the largest creditor with the largest debtor, transferring the minimum of the two amounts, until all balances are zero. This greedy approach yields a valid (though not necessarily minimal) list of paybacks.
Pro tip: Mention that while the greedy approach is simple and correct, minimizing the number of transactions is NP-hard (related to partition), so it's acceptable to return any valid list. Also, clarify how you handle rounding if amounts are not integers.
Confirm the transaction format: each transaction has a sender, a list of recipients, and a total amount split among recipients. Ask whether amounts are integers or floats, and whether the output should be a list of (debtor, creditor, amount) tuples.
Iterate through all transactions and for each user, add the amount they paid and subtract the amount they received. Store net balances in a hash map (or dictionary) mapping user to balance.
Create two lists: one for users with negative net balance (debtors) and one for users with positive net balance (creditors). Optionally, use a max-heap or sort to efficiently pick the largest debtor and creditor.
While both lists are non-empty, take the largest debtor and largest creditor, transfer the minimum of their absolute balances, and update their balances. Remove any user whose balance becomes zero.
Collect each transfer as a payback and return the list. Verify that after applying all paybacks, every user's net balance is zero (or within epsilon for floats).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.