Settle Shared Expenses With a Two-Pointer Payment Plan
Greedy & IntervalsAuto-graded · 21 test casesLast updated
Turn a map of net balances into a deterministic list of payments that zeroes every account, using a sorted two-pointer greedy match between debtors and creditors.
Settle Up: Build the Payment Plan
A group of accounts has tracked shared spending. You are given a dictionary net_balances that maps each account name (a string) to an integer net balance.
- A negative value means the account owes money and must pay.
- A positive value means the account is owed money and must receive.
- A value of
0means the account is already settled. - The sum of all balances is exactly
0.
Return a list of payments that brings every account to a net balance of 0.
Output format
Each payment is a list [payer, receiver, amount], where amount is a positive integer. The function returns a list of such payments.
Required procedure
Because the checker compares your output exactly, build the payments in this deterministic way:
- Collect the debtors (negative balances), recording each one's debt as a positive number. Sort them by account name in ascending (standard string) order.
- Collect the creditors (positive balances) and sort them by account name in ascending order.
- Ignore accounts with a balance of
0. - Keep a pointer at the first debtor and the first creditor. Repeatedly:
- Let
amountbe the smaller of the current debtor's remaining debt and the current creditor's remaining credit. - Append
[debtor_name, creditor_name, amount]to the result. - Subtract
amountfrom both remaining values. - Whichever side reaches
0moves on to the next account in its list (both move on if both reach0). A side with a remainder stays as the current one with its reduced value.
- Let
- Stop when either list is exhausted. By the zero-sum guarantee, both will run out together.
If there is nothing to settle (empty input, or all balances zero), return an empty list.
Constraints
0 <= len(net_balances) <= 10^5- Account names are distinct strings.
- Balances are integers, and their total is exactly
0. - Every payment in the output has
amount > 0, and no account pays itself. - The output must follow the procedure above (sorted order, greedy matching).
Examples
Example 1
Input: settle_up({'A': -5, 'B': 2, 'C': 3})
Output: [['A', 'B', 2], ['A', 'C', 3]]
Example 2
Input: settle_up({'alice': -10, 'bob': 10})
Output: [['alice', 'bob', 10]]
Example 3
Input: settle_up({'A': -7, 'B': -3, 'C': 4, 'D': 6})
Output: [['A', 'C', 4], ['A', 'D', 3], ['B', 'D', 3]]
Hints
Hint 1
Split the accounts into two groups, those who owe and those who are owed, and store debts as positive numbers so both groups look alike. Skip zeros.
Hint 2
Sort each group by account name, then walk both lists with two indices. At each step move min(remaining debt, remaining credit).
Hint 3
After each payment, advance the index of any side that reached zero and keep the reduced remainder for the side that did not. Never emit a zero-amount payment.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Separate the accounts into debtors (negative balances, stored as positive debts) and creditors (positive balances). Zero balances are dropped. Sort each list by account name so the output is deterministic.
Then walk both lists with two pointers. At each step, the current debtor pays the current creditor min(debt, credit). That amount is subtracted from both sides. Any side that hits zero advances to the next account, and a side with a remainder stays put with its reduced value. This resembles the merge step of merge sort.
Why it is correct
- Invariant: total remaining debt always equals total remaining credit. It holds at the start because the balances sum to zero, and each payment subtracts the same amount from both totals.
- No overpayment: paying
min(debt, credit)never exceeds what either side owes or is owed, and an account stays in play only while its remainder is positive, so every amount is strictly positive. - Everyone ends at zero: each loop iteration advances at least one pointer, so the loop terminates. If one list ran out while the other still had a positive remainder, the totals would differ, contradicting the invariant. So both lists are exhausted together and every account is settled.
- Payment count: each payment settles at least one account and the last settles two, so there are at most
d + c - 1payments (ddebtors,ccreditors). This is not always the global minimum, which is NP-hard in general, but the task asks for this specific greedy output.
Complexity
- Time:
O(n log n)for sorting. The two-pointer loop isO(n). - Space:
O(n)for the two lists and the output.
Reference solution
from typing import Dict, List
def settle_up(net_balances: Dict[str, int]) -> List[List[object]]:
debtors = sorted((name, -amt) for name, amt in net_balances.items() if amt < 0)
creditors = sorted((name, amt) for name, amt in net_balances.items() if amt > 0)
payments = []
i = 0
j = 0
while i < len(debtors) and j < len(creditors):
payer, owed = debtors[i]
receiver, due = creditors[j]
amount = min(owed, due)
payments.append([payer, receiver, amount])
owed -= amount
due -= amount
if owed == 0:
i += 1
else:
debtors[i] = (payer, owed)
if due == 0:
j += 1
else:
creditors[j] = (receiver, due)
return payments