Skip to main content

Debt Simplification Algorithm

Editorial

Problem Statement

After a group trip with many shared expenses, the pairwise debt graph between N users can have up to N*(N-1)/2 edges — every pair might owe each other something. If five friends shared 20 expenses, settling individually could require dozens of separate payments.

The goal of debt simplification: Reduce the total number of money transfers needed to settle all debts, while preserving the invariant that every user's net balance reaches zero.

Example: Consider four friends after a trip:

  • Alice is owed $50 net (creditor)
  • Bob owes $30 net (debtor)
  • Charlie owes $20 net (debtor)
  • Diana is owed $0 (balanced — no action needed, but was part of intermediate debts)

Without simplification, there might be 6 individual payments. With simplification: Bob pays Alice $30, Charlie pays Alice $20 — just 2 transfers, and everyone is settled.

Apps like Splitwise and Tricount offer a "Simplify Debts" feature built on this idea (their exact algorithms aren't public).

Approach — Net Balance Greedy Algorithm

The key insight is that individual pairwise debts don't matter for settlement — only net balances do. If Alice owes Bob $10 and Bob owes Alice $7, the net is Alice owes Bob $3. We can collapse the entire debt graph into a single number per user: their net balance.

Algorithm steps:

  1. Compute net balances: For each user, add up their balances with the other users in the group — what they owe counts positive, what they are owed negative, the balance sheet's own sign (a positive value means "I owe them"). This gives one number per user: positive = net debtor, negative = net creditor.

  2. Filter out zero balances: Users with net balance zero don't need to participate in settlements.

  3. Greedy matching: Repeatedly match the largest debtor with the largest creditor:

    • Take the user who owes the most (most positive balance) and the user who is owed the most (most negative balance).
    • The transfer amount is the minimum of the absolute values of their balances.
    • Record a transaction: debtor pays creditor that amount.
    • Update both balances. One (or both) will become zero.
    • Remove zeroed-out users and repeat until all balances are zero.

Why greedy works: Each transaction zeroes out at least one user's balance. With N users having non-zero balances, we need at most N-1 transactions (one user gets zeroed per step, the last two cancel each other).

Conservation invariant: The sum of all net balances is always zero (every dollar owed by someone is owed TO someone). This guarantees the algorithm terminates with everyone at zero.

Step-by-Step Trace

Let's trace the algorithm with a concrete 5-person example from a trip:

After expenses (in the code's sign: positive owes, negative is owed):

  • Alice: net balance = +$60 (owes $60)
  • Bob: net balance = -$40 (owed $40)
  • Charlie: net balance = +$30 (owes $30)
  • Diana: net balance = -$50 (owed $50)
  • Eve: net balance = $0 (balanced)

Verification: +60 + (-40) + 30 + (-50) + 0 = 0 ✓

Step 1: Eve has zero balance → remove. Remaining: Alice(+60), Bob(-40), Charlie(+30), Diana(-50).

Step 2: Largest debtor = Alice(+60). Largest creditor = Diana(-50). Transfer = min(60, 50) = $50. Record: Alice pays Diana $50. New balances: Alice(+10), Bob(-40), Charlie(+30), Diana(0). Remove Diana.

Step 3: Largest debtor = Charlie(+30). Largest creditor = Bob(-40). Transfer = min(30, 40) = $30. Record: Charlie pays Bob $30. New balances: Alice(+10), Bob(-10), Charlie(0). Remove Charlie.

Step 4: Largest debtor = Alice(+10). Largest creditor = Bob(-10). Transfer = min(10, 10) = $10. Record: Alice pays Bob $10. New balances: Alice(0), Bob(0). Both zeroed. Done.

Result: 3 transactions (instead of potentially 10 pairwise settlements):

  1. Alice → Diana: $50
  2. Charlie → Bob: $30
  3. Alice → Bob: $10

Run the Algorithm

Step through DebtSimplifier.simplify() below, on the trace's five friends: their six pairwise debts, one net each, the two max-heaps, then one greedy match at a time — the largest debtor pays the largest creditor the smaller amount, and whoever has money left goes back on the heap — until only its transfers are left, beside the six debts they replace. Three more groups show its edges: one where greedy is not the fewest, a cycle that nets to nothing, and one person who paid for everything. In "Your group", set the nets yourself and compare greedy with the true fewest.

Interactive: debt simplification step by step — pairwise debts, net balances, the debtors' and creditors' max-heaps, each greedy match and its transfer — then only the transfers it made, beside the debts they replace (or, where greedy used more, the fewest); the lesson's trace, a group greedy doesn't settle in the fewest transfers, a cycle, one payer, and your own group against the true fewest.

Implementation

The DebtSimplifier takes a list of users — a group — nets their balances with each other, and returns a list of Transaction objects representing the settlement transfers: at most N-1 of them.

from dataclasses import dataclass
from typing import List
import heapq


@dataclass
class Transaction:
    """A simplified settlement: from_user pays to_user the given amount."""
    from_user: User
    to_user: User
    amount: float

    def __repr__(self) -> str:
        return (f"{self.from_user.name} pays {self.to_user.name}"
                f" ${self.amount:.2f}")


class DebtSimplifier:
    """Settles the given users' debts to each other in at most
    N-1 transactions, with a greedy net-balance approach."""

    def simplify(self, users: List[User]) -> List[Transaction]:
        # Step 1: Compute net balances among these users (a group's debts to each other)
        net_balances: dict[str, float] = {}
        for user in users:
            net = sum(user.balance_sheet.get_balance(other.user_id)
                      for other in users)
            if round(net, 2) != 0:
                net_balances[user.user_id] = round(net, 2)

        # Build lookup for user objects, and each one's place (ties go to the earlier user)
        user_map = {u.user_id: u for u in users}
        order = {u.user_id: i for i, u in enumerate(users)}

        # Step 2: Separate into debtors (positive = owes) and
        # creditors (negative = owed)
        # Use max-heaps (negate for Python's min-heap)
        debtors = []    # (-amount owed, place, user_id): the largest debtor on top
        creditors = []  # (balance, place, user_id), balance < 0: the largest creditor on top

        for uid, balance in net_balances.items():
            if balance > 0:
                # Positive net = this user owes money (debtor)
                heapq.heappush(debtors, (-balance, order[uid], uid))
            elif balance < 0:
                # Negative net = this user is owed money (creditor)
                heapq.heappush(creditors, (balance, order[uid], uid))

        # Step 3: Greedy matching
        transactions: List[Transaction] = []
        while debtors and creditors:
            debt_amt, _, debtor_id = heapq.heappop(debtors)
            credit_amt, _, creditor_id = heapq.heappop(creditors)

            # Convert back from heap representation
            debt_val = -debt_amt     # Positive: how much debtor owes
            credit_val = -credit_amt  # Positive: how much creditor is owed

            transfer = min(debt_val, credit_val)
            transactions.append(Transaction(
                from_user=user_map[debtor_id],
                to_user=user_map[creditor_id],
                amount=round(transfer, 2)
            ))

            # Update remaining balances
            remaining_debt = round(debt_val - transfer, 2)
            remaining_credit = round(credit_val - transfer, 2)

            if remaining_debt > 0:
                heapq.heappush(debtors, (-remaining_debt, order[debtor_id], debtor_id))
            if remaining_credit > 0:
                heapq.heappush(creditors, (-remaining_credit, order[creditor_id], creditor_id))

        return transactions
import java.util.*;

public class Transaction {
    private final User fromUser;
    private final User toUser;
    private final double amount;

    public Transaction(User fromUser, User toUser, double amount) {
        this.fromUser = fromUser;
        this.toUser = toUser;
        this.amount = amount;
    }

    public User getFromUser() { return fromUser; }
    public User getToUser() { return toUser; }
    public double getAmount() { return amount; }

    @Override
    public String toString() {
        return String.format("%s pays %s $%.2f",
            fromUser.getName(), toUser.getName(), amount);
    }
}

public class DebtSimplifier {

    public List<Transaction> simplify(List<User> users) {
        // Step 1: Compute net balances among these users (a group's debts to each other)
        Map<String, Double> netBalances = new LinkedHashMap<>();
        Map<String, User> userMap = new HashMap<>();

        for (User user : users) {
            userMap.put(user.getUserId(), user);
            double net = 0;
            for (User other : users) {
                net += user.getBalance(other.getUserId());
            }
            if (Math.round(net * 100) != 0) {
                netBalances.put(user.getUserId(),
                    Math.round(net * 100.0) / 100.0);
            }
        }

        // Step 2: Separate into debtors and creditors (max-heaps)
        // Debtors: positive balance = owes money; ties go to the earlier user
        Comparator<double[]> largestFirst = (a, b) ->
            a[0] != b[0] ? Double.compare(b[0], a[0]) : Double.compare(a[1], b[1]);
        PriorityQueue<double[]> debtors = new PriorityQueue<>(largestFirst);
        PriorityQueue<double[]> creditors = new PriorityQueue<>(largestFirst);

        // Store userId index mapping for heap entries
        Map<Integer, String> indexToId = new HashMap<>();
        int idx = 0;

        for (Map.Entry<String, Double> entry : netBalances.entrySet()) {
            indexToId.put(idx, entry.getKey());
            if (entry.getValue() > 0) {
                debtors.offer(new double[]{entry.getValue(), idx});
            } else {
                creditors.offer(new double[]{-entry.getValue(), idx});
            }
            idx++;
        }

        // Step 3: Greedy matching
        List<Transaction> transactions = new ArrayList<>();
        while (!debtors.isEmpty() && !creditors.isEmpty()) {
            double[] debtEntry = debtors.poll();
            double[] creditEntry = creditors.poll();

            String debtorId = indexToId.get((int) debtEntry[1]);
            String creditorId = indexToId.get((int) creditEntry[1]);
            double debtVal = debtEntry[0];
            double creditVal = creditEntry[0];

            double transfer = Math.min(debtVal, creditVal);
            transactions.add(new Transaction(
                userMap.get(debtorId),
                userMap.get(creditorId),
                Math.round(transfer * 100.0) / 100.0
            ));

            double remainingDebt =
                Math.round((debtVal - transfer) * 100.0) / 100.0;
            double remainingCredit =
                Math.round((creditVal - transfer) * 100.0) / 100.0;

            if (remainingDebt > 0) {
                debtors.offer(new double[]{remainingDebt, debtEntry[1]});
            }
            if (remainingCredit > 0) {
                creditors.offer(
                    new double[]{remainingCredit, creditEntry[1]});
            }
        }

        return transactions;
    }
}

Complexity Analysis

Time Complexity: Computing the net balances looks up each user's balance with every other user in the group: O(G²) lookups for a group of G users. The greedy part is O(N log N), where N is the number of users with non-zero balances: each step is a heap pop and optionally a heap push — both O(log N) — and since each step zeroes out at least one user, there are at most N-1 steps. Total: O(G² + N log N) — for a group of a few dozen people, instant.

Space Complexity: O(N) for the net balance map, the two heaps, and the output transaction list.

Optimality: The greedy approach guarantees at most N-1 transactions to settle N users, but not always the fewest. With nets of +40, +30 and +20 (owing) against -50 and -40 (owed), greedy makes 4 transfers where 3 suffice: the +40 settles the -40 on its own, and the +30 and +20 settle the -50. Across every ordering of up to five nets from -6 to +6, greedy needed more than the minimum in 840 of 12,088 cases. Finding the true minimum means finding such cancelling subsets — NP-hard (a subset-sum variant) — so greedy's fast, always-settling N-1 bound is the practical choice.

Correctness guarantee: Since the sum of all net balances is zero (conservation of money), the algorithm always terminates with all balances at zero. Each transaction transfers money from a debtor to a creditor, reducing at least one balance to zero.