13. Settle Up Group Trip Expenses
Friends on a trip to Dahab log shared expenses in an app: who paid, how much and who it was for. At the end, the app shows a "Settle up" screen with as few bank transfers as practical.
The app uses a well-known rule: first pair people whose debt and credit match exactly, then repeatedly have the person who owes the most pay the person who is owed the most.
Your task:
- computeBalances(people, expenses): returns { [name]: balance }, where balance = paid - owed.
- settleUp(people, expenses): returns the transfers [{ from, to, amount }] in the order they are generated, using computeBalances.
Rules:
1. Each expense { paidBy, amount, splitAmong } is split equally among splitAmong. Leftover piasters go one each to the first people in splitAmong. The payer is credited the full amount.
2. Positive balances are owed money (creditors). Negative balances owe money (debtors).
3. Exact-match pass: go through the debtors in people order. A debtor whose debt equals the current credit of some creditor pays that creditor (the first such creditor in people order).
4. Greedy pass: while debts remain, the largest debtor pays the largest creditor min(debt, credit). Ties go to the person who comes first in people.
5. Return [] when everyone is already even.
What you'll write
computeBalancesfunctionNet balance per person: paid minus owed.settleUpfunctionThe list of transfers. Uses computeBalances.
Each one has its own test cases, and the last one is also tested together with the others. Implement them in order.
Examples
Example 1
- Function
settleUp- Input
people = ["A", "B", "C"]
expenses = [ { paidBy: "A", amount: 9000, splitAmong: ["A", "B", "C"] }, { paidBy: "B", amount: 3000, splitAmong: ["B", "C"] } ]
- Output
[ { from: "C", to: "A", amount: 4500 }, { from: "B", to: "A", amount: 1500 } ]
- Explanation
- Balances are A +6000, B -1500, C -4500. No exact match, so C (the largest debtor) pays A first, then B pays A.
Solution
Write computeBalances and settleUp. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.
Test Results
Click "Run Code" to test your solution.