KatInterview

Balance and Settle Shared Costs

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashinghash-mapgreedysimulation

Last 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 cost
  • amount: 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 money
  • to: the person receiving money
  • amount: 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 payees per record ≤ 50
  • amount is always evenly divisible by the number of payees
  • All person names are non-empty strings
  • The payer is 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.