Balance and Settle Shared Costs
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests the ability to calculate net balances from shared expense records and generate transfers that zero out all debts.
You're building a feature to settle shared expenses among a group of people.
You receive a list of expense records. Each record is a dictionary containing:
payer: the name of the person who initially covered the entire costamount: the total cost in cents (an integer)payees: a list of people who benefit from this expense and should split it equally
The cost is divided evenly among everyone listed in payees. Note that the payer might also appear in the payees list, meaning they paid for their own portion as well.
Your task is to calculate what direct payments are needed so that everyone ends up even. Return a list of payment instructions, where each instruction is a dictionary with:
from: the person sending moneyto: the person receiving moneyamount: how much to transfer (in cents)
Any valid set of transfers that zeroes out all balances is acceptable. The order of transfers doesn't matter.
Constraints:
- 0 ≤ number of expense records ≤ 1000
- 1 ≤
amount≤ 1,000,000 - 1 ≤ number of
payeesper record ≤ 50 amountis always evenly divisible by the number ofpayees- All person names are non-empty strings
- The
payeris a valid person name
Examples
Example 1
Input: balance_shared_costs([{'payer': 'Alice', 'amount': 4000, 'payees': ['Bob', 'Alice', 'Charlie', 'Daisy']}, {'payer': 'Charlie', 'amount': 2000, 'payees': ['Alice', 'Charlie']}])
Output: [{'from': 'Bob', 'to': 'Alice', 'amount': 1000}, {'from': 'Daisy', 'to': 'Alice', 'amount': 1000}]
Example 2
Input: balance_shared_costs([{'payer': 'A', 'amount': 900, 'payees': ['B', 'C', 'D']}])
Output: [{'from': 'B', 'to': 'A', 'amount': 300}, {'from': 'C', 'to': 'A', 'amount': 300}, {'from': 'D', 'to': 'A', 'amount': 300}]
Example 3
Input: balance_shared_costs([{'payer': 'A', 'amount': 1000, 'payees': ['A', 'B']}, {'payer': 'B', 'amount': 600, 'payees': ['B', 'C']}, {'payer': 'C', 'amount': 400, 'payees': ['A', 'C']}])
Output: [{'from': 'B', 'to': 'A', 'amount': 200}, {'from': 'C', 'to': 'A', 'amount': 100}]
Hints
Hint 1
First calculate each person's net balance: how much they paid minus how much they owe from all shared expenses.
Hint 2
People with negative balances need to pay; people with positive balances should receive. The sum of all balances is always zero.
Hint 3
Use a two-pointer approach: match people who owe money with people who are owed money, transferring the minimum of what's owed and what's due each time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution works in three phases:
Phase 1: Calculate net balances. For each expense record, credit the payer with the full amount they paid. Then debit each payee for their equal share. If the payer is also listed among the payees, both adjustments apply, leaving them credited only for what others owe them. Track all balances in a dictionary.
Phase 2: Separate into two groups. Split people into those who owe money (negative balance) and those who are owed money (positive balance). Sort both groups by name for deterministic output. People with zero balance require no transfers.
Phase 3: Match payers with receivers. Use two pointers to walk through the two sorted lists simultaneously. At each step, the current debtor pays the current creditor the smaller of what they owe or what is owed to the creditor. This zeroes out at least one person's balance, allowing us to advance at least one pointer. Continue until all balances are settled.
Why It Works
The key insight is that individual transactions don't matter once you know each person's net position. Since every cent paid out is owed by someone, the total of all balances is always zero—the amount owed by debtors exactly equals the amount due to creditors.
The greedy matching guarantees correctness: each transfer moves exactly what can be settled between the current pair without overpayment. When one person's balance reaches zero, we move to the next. Because the totals match, both lists exhaust simultaneously, leaving everyone even.
This produces at most D + C - 1 transfers, where D is the number of debtors and C is the number of creditors (one fewer than the number of people with non-zero balances).
Complexity
Let E be the number of expense records, P be the total number of payees across all records, and N be the number of distinct people.
-
Time complexity: O(E + P + N log N)
- Computing balances requires visiting each payee entry once: O(P)
- Sorting debtors and creditors: O(N log N)
- The two-pointer matching runs at most N-1 iterations: O(N)
-
Space complexity: O(N)
- The balance dictionary stores up to N entries
- The debtor and creditor lists combined contain at most N entries
- The output list contains at most N-1 transfers
Solution Code
from typing import List, Dict
def balance_shared_costs(expenses: List[Dict]) -> List[Dict]:
balances = {}
def update_balance(person, amount):
balances[person] = balances.get(person, 0) + amount
for expense in expenses:
payer = expense["payer"]
amount = expense["amount"]
payees = expense["payees"]
per_person = amount // len(payees)
update_balance(payer, amount)
for payee in payees:
update_balance(payee, -per_person)
owes = sorted((person, -balance) for person, balance in balances.items() if balance < 0)
owed = sorted((person, balance) for person, balance in balances.items() if balance > 0)
result = []
i = 0
j = 0
while i < len(owes) and j < len(owed):
debtor, debt = owes[i]
creditor, credit = owed[j]
transfer = min(debt, credit)
result.append({"from": debtor, "to": creditor, "amount": transfer})
debt -= transfer
credit -= transfer
if debt == 0:
i += 1
else:
owes[i] = (debtor, debt)
if credit == 0:
j += 1
else:
owed[j] = (creditor, credit)
return result