Group Expense Balancer: Greedy vs Optimal Settlement
Data Structure DesignAuto-graded · 26 test casesLast updated
Tests ability to implement both a greedy two-pointer debt-clearing algorithm and an exact minimum-transaction settlement using memoized recursion.
Group Expense Balancer: Greedy vs Optimal Settlement
A group of people track shared expenses. After all costs are recorded and split, each person ends up with a net position: a positive value means the group owes them money, a negative value means they owe the group money.
Your job is to turn a map of these net positions into two settlement plans that clear every balance to zero.
Input
A dictionary net_positions mapping each person's name (str) to their net balance (int). Positive means owed to them; negative means they owe others. You may assume the values sum to zero. Zero-balance entries should be ignored.
Output
Return a single dictionary with two keys:
{
"settle": {
"transactions": [...],
"count": <int>
},
"settle_optimally": {
"transactions": [...],
"count": <int>
}
}
Each entry in transactions is a three-element list [payer, payee, amount] meaning payer sends amount to payee.
settle — Greedy Plan
Use a two-pointer greedy approach:
- Separate people into debtors (negative balance) and creditors (positive balance).
- Sort both groups by name so the output is deterministic.
- At each step, match the first debtor with the first creditor. The payment amount is
min(|debtor's balance|, creditor's balance). Advance whichever pointer is now exhausted (or both if they cancel exactly). - Repeat until all balances are zero.
This produces at most n − 1 transactions for n people. It does not guarantee the minimum.
settle_optimally — Minimum-Transaction Plan
Find the settlement plan that uses the fewest possible transactions.
Use memoized recursion over the tuple of current balances:
- Find the first person with a negative balance.
- Try pairing them with every person who has a positive balance. Transfer
min(|negative|, positive)between them to zero out at least one side. - Recurse on the resulting state. Memoize by the full balance tuple.
- Among all complete plans, keep the one with the fewest transactions. Break ties lexicographically (compare the transaction tuples directly).
The names are fixed in sorted order so the state tuple maps back to names consistently.
Constraints
1 ≤ len(net_positions) ≤ 8- All values are integers;
sum(net_positions.values()) == 0 - Names are non-empty strings containing only uppercase letters
- Amounts fit in a 32-bit signed integer
- If all balances are zero, both plans return empty transaction lists
Examples
Example 1
Input: settlement_plans({'A': 20, 'B': 10, 'C': -10, 'D': -20})
Output: {'settle': {'transactions': [['C', 'A', 10], ['D', 'A', 10], ['D', 'B', 10]], 'count': 3}, 'settle_optimally': {'transactions': [['C', 'B', 10], ['D', 'A', 20]], 'count': 2}}
Example 2
Input: settlement_plans({'A': 5, 'B': -5})
Output: {'settle': {'transactions': [['B', 'A', 5]], 'count': 1}, 'settle_optimally': {'transactions': [['B', 'A', 5]], 'count': 1}}
Example 3
Input: settlement_plans({'A': -10, 'B': -10, 'C': 20})
Output: {'settle': {'transactions': [['A', 'C', 10], ['B', 'C', 10]], 'count': 2}, 'settle_optimally': {'transactions': [['A', 'C', 10], ['B', 'C', 10]], 'count': 2}}
Example 4
Input: settlement_plans({'A': 0, 'B': 0})
Output: {'settle': {'transactions': [], 'count': 0}, 'settle_optimally': {'transactions': [], 'count': 0}}
Hints
Hint 1
Split the net_positions dict into two lists — one for people who owe money (negative balance) and one for people who are owed money (positive balance). Sorting both lists by name keeps the greedy output deterministic.
Hint 2
For the optimal solution, represent the current state as a tuple of balances (in a fixed name order). Memoize on that tuple so you never recompute the same partial state twice.
Hint 3
The minimum number of transactions equals the number of people whose balance is non-zero after netting, minus the maximum number of balances you can cancel in a single chain. A simpler bound: it can never be less than max(number of debtors, number of creditors).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reducing to net positions
Before either algorithm runs, zero-balance entries are stripped and the remaining names are sorted. Sorting is the key to deterministic output: both the greedy walk and the recursion encounter names in the same order every time, so tie-breaking is consistent across runs.
The invariant sum == 0 is checked upfront. If it fails the input is malformed — no settlement plan exists.
Greedy plan (settle)
Separate the non-zero entries into two lists:
- debtors — people with a negative net balance (they owe money)
- creditors — people with a positive net balance (they are owed money)
Both lists inherit the sorted order from the balances dict. Then run two pointers, one into each list:
- The payment amount is
min(|debtor's remaining debt|, creditor's remaining credit). - Record
[debtor_name, creditor_name, amount]. - Subtract the amount from both sides. Advance whichever pointer reached zero (or both if they cancelled exactly).
Each step zeroes out at least one person, so the loop runs at most n − 1 times for n non-zero participants. In the worst case (one creditor, many debtors, or vice versa) you get exactly n − 1 transactions — which is provably the upper bound for any correct algorithm.
Why it is correct but not always minimal: the greedy pairs the first available debtor with the first available creditor. It misses cases where two people's balances cancel each other exactly across a longer chain.
Optimal plan (settle_optimally)
This is a memoized exhaustive search over the space of balance states.
State: a tuple of integer balances in fixed name order. The tuple uniquely describes the remaining obligations; name order never changes so indices always map to the same person.
Recursion:
- Find the first index
iwhere the balance is negative (the first debtor). - Try every creditor
j(positive balance). Transfermin(|balance[i]|, balance[j])— this zeroes out at least one of them. - Recurse on the new state. Prepend the current transaction to the result.
- Among all complete plans found across the
jloop, keep the one with the fewest transactions. Ties are broken by comparing the full tuple of transactions lexicographically, which makes the output deterministic. - Memoize the result keyed on the state tuple so overlapping sub-problems are solved only once.
Why it is optimal: the recursion considers every possible pairing for the current debtor and recurses over the full remaining problem. No reachable state is skipped. Memoization ensures each unique state is solved exactly once, so the algorithm is exhaustive without redundant work.
Why it terminates: every recursive call zeroes out at least one balance, strictly reducing the number of non-zero entries. The recursion depth is bounded by n.
Minimum bound argument: a person with a non-zero balance must appear in at least one transaction. If there are d debtors and c creditors after netting, any valid settlement needs at least max(d, c) transactions. The optimal algorithm achieves this when the balances allow it (e.g. when some debtor/creditor pairs cancel exactly).
Complexity
| Time | Space | |
|---|---|---|
| Greedy | O(n log n) — dominated by the sort | O(n) |
| Optimal | O(n · S) where S is the number of distinct reachable states | O(S) for the memo table |
The state space S grows quickly with n, but since the constraint caps the group at 8 members the exact search completes instantly in practice. For larger groups (say n > 15) you would switch to a heuristic or approximation.
Reference solution
from typing import Dict
def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]:
balances = {name: amount for name, amount in sorted(net_positions.items()) if amount}
if sum(balances.values()) != 0:
raise ValueError("net positions must sum to zero")
def greedy_plan(values):
debtors = [[name, -amount] for name, amount in values.items() if amount < 0]
creditors = [[name, amount] for name, amount in values.items() if amount > 0]
result = []
i = j = 0
while i < len(debtors) and j < len(creditors):
amount = min(debtors[i][1], creditors[j][1])
result.append([debtors[i][0], creditors[j][0], amount])
debtors[i][1] -= amount
creditors[j][1] -= amount
if debtors[i][1] == 0:
i += 1
if creditors[j][1] == 0:
j += 1
return result
names = list(balances)
initial = tuple(balances[name] for name in names)
memo = {}
def solve(state):
if state in memo:
return memo[state]
i = next((idx for idx, v in enumerate(state) if v < 0), None)
if i is None:
return ()
best = None
for j, v in enumerate(state):
if v <= 0:
continue
amount = min(-state[i], v)
next_state = list(state)
next_state[i] += amount
next_state[j] -= amount
suffix = solve(tuple(next_state))
candidate = ((names[i], names[j], amount),) + suffix
if best is None or (len(candidate), candidate) < (len(best), best):
best = candidate
memo[state] = best
return best
greedy = greedy_plan(balances)
optimal = [list(payment) for payment in solve(initial)]
return {
"settle": {"transactions": greedy, "count": len(greedy)},
"settle_optimally": {"transactions": optimal, "count": len(optimal)},
}