Settle Group Expenses with Transfers
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to compute and reconcile per-person financial balances from transactional data and to translate net liabilities into direct transfers, exercising skills in numeric bookkeeping and data aggregation.
Constraints
- 0 <= len(transactions) <= 100000
- 1 <= total number of payee entries across all transactions <= 200000, unless transactions is empty
- Each transaction has at least one payee
- Within a transaction, payees are unique
- 0 <= amount <= 1000000000000
- For every transaction, amount is evenly divisible by len(payees)
- Person names are non-empty strings
Examples
Input: ([{'payer': 'Alice', 'amount': 4000, 'payees': ['Bob', 'Alice', 'Charlie', 'Daisy']}, {'payer': 'Charlie', 'amount': 2000, 'payees': ['Alice', 'Charlie']}],)
Expected Output: [{'from': 'Bob', 'to': 'Alice', 'amount': 1000}, {'from': 'Daisy', 'to': 'Alice', 'amount': 1000}]
Explanation: Alice is owed 2000 total. Bob and Daisy each owe 1000. Charlie's balance is already zero.
Input: ([] ,)
Expected Output: []
Explanation: There are no transactions, so no transfers are needed.
Input: ([{'payer': 'Ava', 'amount': 750, 'payees': ['Ava']}],)
Expected Output: []
Explanation: Ava paid 750 and was the only payee, so Ava's paid amount exactly equals Ava's own share.
Input: ([{'payer': 'Mia', 'amount': 1200, 'payees': ['Ann', 'Ben', 'Cat']}],)
Expected Output: [{'from': 'Ann', 'to': 'Mia', 'amount': 400}, {'from': 'Ben', 'to': 'Mia', 'amount': 400}, {'from': 'Cat', 'to': 'Mia', 'amount': 400}]
Explanation: Mia paid for Ann, Ben, and Cat, but did not share the expense herself. Each payee owes Mia 400.
Input: ([{'payer': 'A', 'amount': 3000, 'payees': ['A', 'B', 'C']}, {'payer': 'D', 'amount': 1500, 'payees': ['B', 'C', 'D']}, {'payer': 'B', 'amount': 1000, 'payees': ['A', 'B']}],)
Expected Output: [{'from': 'B', 'to': 'A', 'amount': 1000}, {'from': 'C', 'to': 'A', 'amount': 500}, {'from': 'C', 'to': 'D', 'amount': 1000}]
Explanation: Final balances are A: +1500, D: +1000, B: -1000, C: -1500. The listed transfers settle all four balances.
Hints
- Track each person's net balance: add the full amount to the payer, then subtract one equal share from every payee.
- After computing balances, separate people who owe money from people who should receive money, then greedily match them.