Load/Bearing
Low-level design · 21 of 22

Splitwise: expenses, splits and settling up

Model shared expenses so equal, exact and percentage splits share one code path, then settle the group in as few payments as practical.

4 min read

Splitwise tracks who paid for what in a group and who owes whom. It's a good LLD problem because it has a real model, a real algorithm, and one classic trap: rounding money.

The model

Store money as long cents (or paise). A ₹100 bill split three ways is 3,334 + 3,333 + 3,333 paise, and someone has to get the extra paisa.

Three split types, one code path

The trick: every split is a weighted split. Equal is weight 1 each. Percentage is weights in basis points that must add up to 10,000. Exact amounts are weights equal to the amounts, which must add up to the total. So there's one function for the arithmetic, and each split type only validates its input and builds weights.

final class Splits {
    /** Splits totalCents in proportion to weights. Leftover cents go to the largest remainders,
     *  so the parts always add up exactly to the total. */
    static Map<String, Long> byWeight(long totalCents, Map<String, Long> weights) {
        long sum = weights.values().stream().mapToLong(Long::longValue).sum();
        if (sum <= 0) throw new IllegalArgumentException("weights must add up to more than zero");
        Map<String, Long> parts = new LinkedHashMap<>();
        List<Map.Entry<String, Long>> remainders = new ArrayList<>();
        long assigned = 0;
        for (Map.Entry<String, Long> w : weights.entrySet()) {
            long scaled = totalCents * w.getValue();
            parts.put(w.getKey(), scaled / sum);
            assigned += scaled / sum;
            remainders.add(Map.entry(w.getKey(), scaled % sum));
        }
        remainders.sort(Map.Entry.<String, Long>comparingByValue().reversed());
        for (int i = 0; i < totalCents - assigned; i++) {
            parts.merge(remainders.get(i).getKey(), 1L, Long::sum);
        }
        return parts;
    }

    // Each split type is only validation plus weights. There is one code path for the arithmetic.
    static Map<String, Long> equal(long totalCents, List<String> people) {
        Map<String, Long> weights = new LinkedHashMap<>();
        people.forEach(p -> weights.put(p, 1L));
        return byWeight(totalCents, weights);
    }

    static Map<String, Long> percent(long totalCents, Map<String, Long> basisPoints) {
        require(sum(basisPoints) == 10_000, "percentages must add up to 100%");
        return byWeight(totalCents, basisPoints);
    }

    static Map<String, Long> exact(long totalCents, Map<String, Long> cents) {
        require(sum(cents) == totalCents, "amounts must add up to the total");
        return byWeight(totalCents, cents);          // weights equal to the amounts reproduce them exactly
    }

    private static long sum(Map<String, Long> m) { return m.values().stream().mapToLong(Long::longValue).sum(); }
    private static void require(boolean ok, String message) { if (!ok) throw new IllegalArgumentException(message); }
}

Leftover cents go to the people with the largest remainders (the "largest remainder method"), so every split adds up to the exact total and the extra cent lands where the rounding error was biggest. New types, such as "by shares" (2 shares for an adult, 1 for a child), are just more weights.

Balances and settling up

Don't track who owes whom pair by pair. Each expense just adjusts every participant's net balance. To settle up, match people who owe with people who are owed:

record Expense(String id, String paidBy, long totalCents, Map<String, Long> owed) {}
record Transfer(String from, String to, long cents) {}

final class Group {
    private final Map<String, Long> net = new HashMap<>();   // positive: is owed; negative: owes

    void add(Expense e) {
        net.merge(e.paidBy(), e.totalCents(), Long::sum);
        e.owed().forEach((person, cents) -> net.merge(person, -cents, Long::sum));
    }

    Map<String, Long> balances() { return Map.copyOf(net); }

    /** Greedy settlement: largest debtor pays largest creditor. At most n - 1 transfers, O(n log n). */
    List<Transfer> settle() {
        Comparator<Map.Entry<String, Long>> bySize = Comparator.comparingLong(e -> Math.abs(e.getValue()));
        PriorityQueue<Map.Entry<String, Long>> creditors = new PriorityQueue<>(bySize.reversed());
        PriorityQueue<Map.Entry<String, Long>> debtors = new PriorityQueue<>(bySize.reversed());
        net.forEach((person, cents) -> {
            if (cents > 0) creditors.add(Map.entry(person, cents));
            else if (cents < 0) debtors.add(Map.entry(person, cents));
        });

        List<Transfer> transfers = new ArrayList<>();
        while (!creditors.isEmpty()) {
            Map.Entry<String, Long> c = creditors.poll(), d = debtors.poll();
            long pay = Math.min(c.getValue(), -d.getValue());
            transfers.add(new Transfer(d.getKey(), c.getKey(), pay));
            if (c.getValue() > pay) creditors.add(Map.entry(c.getKey(), c.getValue() - pay));
            if (-d.getValue() > pay) debtors.add(Map.entry(d.getKey(), d.getValue() + pay));
        }
        return transfers;
    }
}

The greedy algorithm always pays the largest debt to the largest credit. Each transfer settles at least one person completely, so a group of n people needs at most n − 1 transfers, and with two heaps it runs in O(n log n).

Is it optimal? Not always. Finding the true minimum number of transfers is NP-hard: it's equivalent to splitting the balances into as many groups that sum to zero as possible. For small groups you can solve it exactly with a search over subsets in O(2ⁿ) (LeetCode 465, "Optimal Account Balancing"). In an interview, say that greedy is the practical answer, give its bound, and mention the exact version.

Things to mention

Interview checklist

Practise it

Exercise

Implement Splits and Group, then test: ₹100 split three ways sums to exactly ₹100; percentages that don't add to 100% are rejected; and after settle(), applying the transfers leaves every balance at zero.

Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

Settle up

Further reading