LLD

Full Designs

Splitwise

A weak answer draws users, groups and expenses and stops. We build one that holds up when the interviewer pushes: how $100 splits three ways without losing a cent, what the group stores, how a pile of debts becomes three payments, and what happens when two phones add an expense at once.

"Design Splitwise" sounds like an app that only stores and lists records. A weak answer draws a User, a Group, an Expense and a Split, stores who owes whom in a table, and stops. The classes are right, and the hard parts have not been touched.

The interviewer wants to see what happens at the edges. $100 split three ways is $33.33 each, which adds up to $99.99, so where does the last cent go? Does the group store every debt between every pair of people, or something smaller? How does a page of debts become a short list of payments? What happens when two people add an expense to the same group at the same moment?

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

Splitwise at a glance
A member adds an expense with a split rule (1). The rule turns the bill into shares that add up to it exactly (2). The group checks every name and moves every balance in one locked step (3). From the balances, the group works out a short list of payments that would settle everyone (4). When a member pays another, settleUp records it and moves both balances (5).A member adds an expense with a split rule (1). The rule turns the bill into shares that add up to it exactly (2). The group checks every name and moves every balance in one locked step (3). From the balances, the group works out a short list of payments that would settle everyone (4). When a member pays another, settleUp records it and moves both balances (5).
An expense changes balances. Balances become a short list of payments. A member adds an expense with a split rule (1). The rule turns the bill into shares that add up to it exactly (2). The group checks every name and moves every balance in one locked step (3). From the balances, the group works out a short list of payments that would settle everyone (4). When a member pays another, settleUp records it and moves both balances (5).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Who can share an expense?Members of a group. Two friends sharing a bill are a group of twoGroup is the unit, and every name is checked against it
How can a bill be split?Equally, by exact amounts, or by percentageOne interface for split rules, with three implementations
Can someone pay without sharing?Yes, a person can pay for othersThe payer and the people sharing are separate inputs
Can several people pay one bill?No, one payer per expenseExpense has one paidBy
Which currency?Dollars only, to the centMoney is a whole number of cents
What does a member see?Their balance in the group, and who should pay whomOne net balance per member, and a plan of payments
How do people settle up?One member records a cash or UPI payment to anotherA settleUp method that moves two balances
Can expenses be edited or deleted?Not in this versionExpenses are records that never change
Do people add expenses at the same time?Yes, from several phonesThe group must be safe to call from many threads

The currency question matters more than it looks. "To the cent" means a split must divide a bill into whole cents and still add up to the bill. That rules out double, and it forces a decision about where leftover cents go.

Requirements

Functional:

  1. A member adds an expense: who paid, how much, and how it is split, equally, by exact amounts or by percentage. The shares add up to the bill exactly, to the cent.
  2. An expense whose split does not work out, or that names someone outside the group, is refused, and nothing in the group changes.
  3. Each member can see their balance in the group: how much they are owed, or how much they owe.
  4. The group can suggest a short list of payments that would settle everyone.
  5. A member records a payment to another member, and both balances change.

Out of scope: editing or deleting an expense, several payers on one bill, several currencies, reminders, and photos of receipts. We come back to these at the end, because each is a natural follow-up, and a design that bends towards them is part of the answer.

Everything lives in memory, as is normal for a low-level design interview. Saving groups so they survive a restart is a storage question for a separate discussion.

What the code itself must handle:

  • Exact money. No cent is created or lost, however a bill is split.
  • Many phones at once. addExpense and settleUp will be called from several threads on the same group.
  • Rules that change. A new way of splitting, such as by shares, should not mean editing the group.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
Group, member, expense, payment and amount become classes or records. The way a bill is split becomes an interface with three implementations. Working out who should pay whom becomes DebtSimplifier, and each planned payment a Transfer. Three nouns are crossed out. A debt between two people can be worked out from the balances, so it is not stored. A notification and a receipt photo are outside this design.Group, member, expense, payment and amount become classes or records. The way a bill is split becomes an interface with three implementations. Working out who should pay whom becomes DebtSimplifier, and each planned payment a Transfer. Three nouns are crossed out. A debt between two people can be worked out from the balances, so it is not stored. A notification and a receipt photo are outside this design.
Most nouns become classes. The debt between two people does not. Group, member, expense, payment and amount become classes or records. The way a bill is split becomes an interface with three implementations. Working out who should pay whom becomes DebtSimplifier, and each planned payment a Transfer. Three nouns are crossed out. A debt between two people can be worked out from the balances, so it is not stored. A notification and a receipt photo are outside this design.

The noun that needs the most thought is debt. "Ravi owes Asha $50" sounds like a fact the app must store. It is a result of the expenses so far, and the group can store something much smaller.

Decision

Store who owes whom, or one balance per member?

A debt for every pair of members

This matches what people say out loud. But a group of 10 has 45 pairs, every expense updates several of them, and the same money can go round in a circle: Asha owes Ravi, Ravi owes Meera, Meera owes Asha. The table grows, and every answer to "who should pay whom?" needs it simplified first anyway.

One net balance per memberOur pick

Each member has one number. Positive means the group owes them, and negative means they owe the group. An expense adds the bill to the payer and subtracts each share from the person it belongs to. The numbers always add up to zero, which gives the design one rule to check. Who pays whom is worked out from the balances when someone asks. The list of expenses is kept too, so nothing about the history is lost.

Data or behaviour?

Some classes only carry data and never change once created: a user, an expense, a payment, a planned transfer, an amount of money. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.

expense/Expense.javalines 10–14 of 14
public record Expense(String id, String description, User paidBy, Money amount, Map<User, Money> shares) {    public Expense {        shares = Collections.unmodifiableMap(new LinkedHashMap<>(shares));    }}

The compact constructor copies the shares into an unmodifiable map, so nobody can change an expense's shares after it is recorded.

User is a record too, with one change. A record's equals compares every field, so the same person with a new name would count as a second member. User overrides equals and hashCode to compare the id alone:

user/User.javalines 15–23 of 29
    @Override    public boolean equals(Object other) {        return other instanceof User user && id.equals(user.id);    }     @Override    public int hashCode() {        return id.hashCode();    }

A member who changes their name is still the same member, and the tie-breaks later in the article can rely on every id being different. The group keeps the User it was given when the member joined, so it shows that name. Showing a new name needs the app to look names up by id.

The class diagram

The classes and how they connect
Group owns the balance map, the list of expenses and the list of payments. It takes a SplitRule for each expense and never knows which rule it has. EqualSplit, ExactSplit and PercentSplit implement SplitRule. EqualSplit and PercentSplit share the Proportional helper. Group is also given a DebtSimplifier when it is created, which turns a copy of the balances into a list of Transfers. GreedySimplifier implements it. User, Expense, Payment, Transfer and Money are records: data with no behaviour beyond small helpers.Group owns the balance map, the list of expenses and the list of payments. It takes a SplitRule for each expense and never knows which rule it has. EqualSplit, ExactSplit and PercentSplit implement SplitRule. EqualSplit and PercentSplit share the Proportional helper. Group is also given a DebtSimplifier when it is created, which turns a copy of the balances into a list of Transfers. GreedySimplifier implements it. User, Expense, Payment, Transfer and Money are records: data with no behaviour beyond small helpers.
Group holds the balances. Split rules turn a bill into shares. Group owns the balance map, the list of expenses and the list of payments. It takes a SplitRule for each expense and never knows which rule it has. EqualSplit, ExactSplit and PercentSplit implement SplitRule. EqualSplit and PercentSplit share the Proportional helper. Group is also given a DebtSimplifier when it is created, which turns a copy of the balances into a list of Transfers. GreedySimplifier implements it. User, Expense, Payment, Transfer and Money are records: data with no behaviour beyond small helpers.

The classes fall into three groups:

  • Data: User, Money, Expense, Payment and Transfer. These are records.
  • The core: Group. It holds the only state that changes, the balances and the history, and keeps it correct under many threads.
  • Rules: SplitRule and its three implementations, which turn a bill into shares, and DebtSimplifier with GreedySimplifier, which turn balances into payments. None of them holds any state that changes.

The rest of the article builds these one at a time.

Building it

Money in cents

Every amount in the design is a Money, a record around a long number of cents.

money/Money.javalines 7–28 of 50
public record Money(long cents) implements Comparable<Money> {    public static final Money ZERO = new Money(0);     public static Money ofCents(long cents) {        return new Money(cents);    }     public static Money dollars(long dollars) {        return new Money(Math.multiplyExact(dollars, 100));    }     public Money plus(Money other) {        return new Money(Math.addExact(cents, other.cents));    }     public Money minus(Money other) {        return new Money(Math.subtractExact(cents, other.cents));    }     public Money negate() {        return new Money(Math.negateExact(cents));    }

dollars(900) stores 90,000 cents. plus, minus and negate use Math.addExact and its siblings, so an amount too big for a long throws an ArithmeticException instead of quietly wrapping round to a negative number. A Money may be negative, because a balance can be.

Decision

How should money be stored?

A double of dollars

It reads naturally, but 0.1 + 0.2 is not exactly 0.3 in floating point. After enough expenses, the balances can add up to a tiny fraction instead of zero, and "is this member settled?" has no clean answer.

A BigDecimal of dollars

It is exact. But every split then needs a rounding mode and a scale, and two BigDecimal values that look equal ($5.0 and $5.00) are not equals.

A long of cents, inside a small Money recordOur pick

Cents are whole numbers, so adding and subtracting are exact, and two equal amounts are always equals. The record stops a balance from being mixed up with a count or a percentage, which a bare long would allow. It also puts the overflow checks in one place. A long holds more cents than any group will ever spend.

Splitting a bill

There is more than one way to split a bill, and the app will want more later: by shares, by nights stayed, by what each person ordered. This is the first place the design needs a pattern.

split/SplitRule.javalines 9–15 of 15
public interface SplitRule {    /**     * Each participant's share. The shares always add up to {@code total} exactly,     * or this throws InvalidSplitException.     */    Map<User, Money> split(Money total);}

The interface makes one promise: the shares add up to the total exactly, or split throws an InvalidSplitException. Each rule holds the people it covers and anything else it needs, such as the typed amounts or the percentages. So split needs only the total.

An equal split looks trivial until the bill does not divide. $100 among three people is 10,000 cents among three, and 10,000 is not a multiple of 3. If each share is rounded down to $33.33, the shares add up to $99.99, and the cent that is left over belongs to nobody. Over a year of dinners, the group's balances would stop adding up to zero.

Where the last cent goes
$100 split three ways is 3,333.33 cents each. Rounding down gives 3,333 cents to Asha, Meera and Ravi, which is 9,999 cents, one short of the bill. The one cent left over goes to the share that lost the most in rounding. All three lost the same, so the tie goes to the lowest user id, asha. Asha pays $33.34 and the others pay $33.33.$100 split three ways is 3,333.33 cents each. Rounding down gives 3,333 cents to Asha, Meera and Ravi, which is 9,999 cents, one short of the bill. The one cent left over goes to the share that lost the most in rounding. All three lost the same, so the tie goes to the lowest user id, asha. Asha pays $33.34 and the others pay $33.33.
Round every share down, then hand out what is left, one cent at a time. $100 split three ways is 3,333.33 cents each. Rounding down gives 3,333 cents to Asha, Meera and Ravi, which is 9,999 cents, one short of the bill. The one cent left over goes to the share that lost the most in rounding. All three lost the same, so the tie goes to the lowest user id, asha. Asha pays $33.34 and the others pay $33.33.

EqualSplit and PercentSplit both hand the work to one helper, Proportional, which divides a total in proportion to whole-number weights. An equal split gives everyone a weight of 1. A percentage split uses the percentages.

split/Proportional.javalines 18–43 of 63
    static Map<User, Money> allocate(Money total, Map<User, Long> weights) {        if (total.isNegative()) {            throw new IllegalArgumentException("A total cannot be negative: " + total);        }        // Users in id order, so the same bill always splits the same way.        List<User> users = new ArrayList<>(weights.keySet());        users.sort(Comparator.comparing(User::id));         long weightSum = 0;        for (User user : users) {            weightSum = Math.addExact(weightSum, weights.get(user));        }        if (weightSum <= 0) {            throw new InvalidSplitException("Nobody has a share of this bill");        }         int n = users.size();        long[] shares = new long[n];        long[] remainders = new long[n];        long given = 0;        for (int i = 0; i < n; i++) {            long exact = Math.multiplyExact(total.cents(), weights.get(users.get(i)));            shares[i] = exact / weightSum;            remainders[i] = exact % weightSum;            given += shares[i];        }

First the helper refuses a negative total. Then it sorts the people by id. Then, for each person, it multiplies the total by their weight and divides by the sum of the weights. The quotient, rounded down, is their share so far. The remainder says how much they lost in rounding.

split/Proportional.javalines 45–61 of 63
        // Rounding down left fewer than n cents over. Each goes to the largest remainder.        long leftover = total.cents() - given;        List<Integer> order = new ArrayList<>();        for (int i = 0; i < n; i++) {            order.add(i);        }        order.sort(Comparator.comparingLong((Integer i) -> remainders[i]).reversed()                .thenComparingInt(i -> i));        for (int k = 0; k < leftover; k++) {            shares[order.get(k)]++;        }         Map<User, Money> result = new LinkedHashMap<>();        for (int i = 0; i < n; i++) {            result.put(users.get(i), Money.ofCents(shares[i]));        }        return result;

The shares rounded down never add up to more than the total, and they fall short by fewer cents than there are people. Those leftover cents go out one at a time, to the people with the largest remainders first. Ties go to the lower id, which is the order the list was sorted into.

Decision

Who gets the leftover cents?

The person who paid the bill

This is simple. But for a percentage split the leftover then has nothing to do with the percentages. In a 50/30/20 split of $10.01 paid by the 20% person, the payer takes the cent, although the 50% person's share lost the most in rounding.

Round each share to the nearest cent and accept the gap

Each share is as close as it can be. But $100 three ways rounds to $33.33 three times, and the cent is gone. Two shares that both end in .5 can also round up together, which creates a cent. The balances then drift away from zero, and nobody can say where the difference went.

The largest remainders, ties to the lowest idOur pick

The leftover goes to the shares that were cut the most, so every share stays within one cent of its exact value. The total is always exact. Breaking ties by id means the same bill always splits the same way, whatever order the names were typed in, so a test or a support person can predict every share.

Exact amounts and percentages

With an exact split, the person entering the bill types each share. The rule has nothing to calculate, but it must check the arithmetic:

split/ExactSplit.javalines 36–47 of 48
    @Override    public Map<User, Money> split(Money total) {        Objects.requireNonNull(total, "total");        Money sum = Money.ZERO;        for (Money share : shares.values()) {            sum = sum.plus(share);        }        if (!sum.equals(total)) {            throw new InvalidSplitException("The shares add up to " + sum + ", not " + total);        }        return new LinkedHashMap<>(shares);    }

If Meera pays $120 for a cab and types $30 for Asha and $80 for Kabir, the shares add up to $110, and the expense is refused with that message. The constructor has already refused a negative share and an empty split.

A percentage split checks its percentages when it is created:

split/PercentSplit.javalines 15–29 of 36
    public PercentSplit(Map<User, Integer> percents) {        int sum = 0;        for (Map.Entry<User, Integer> entry : percents.entrySet()) {            User user = Objects.requireNonNull(entry.getKey(), "user");            int percent = Objects.requireNonNull(entry.getValue(), "percent");            if (percent < 0 || percent > 100) {                throw new InvalidSplitException(user + "'s percentage must be between 0 and 100");            }            sum += percent;            this.percents.put(user, (long) percent);        }        if (sum != 100) {            throw new InvalidSplitException("The percentages add up to " + sum + ", not 100");        }    }

Each percentage must be a whole number from 0 to 100, and together they must make exactly 100. The rule then uses Proportional with the percentages as weights. A 20/40/40 split of $600 divides cleanly into $120, $240 and $240. A 50/30/20 split of $10.01 gives $5.00, $3.00 and $2.00 after rounding down, and the one leftover cent goes to the 50% person, whose exact share of $5.005 lost the most.

There are two kinds of error here, and they are kept apart. A mistake a person can make while typing, a split that does not add up or a name outside the group, throws an InvalidSplitException or a NotAMemberException with a message the app can show. Input the screen checks before sending it, a null, an amount of zero or less, or an expense over Group.MAX_AMOUNT of $100,000, throws NullPointerException or IllegalArgumentException. The cap applies to expenses only. A payment settles a balance, and a balance can grow past any one expense, so a payment has no cap. For payments, the guard is Money: a payment that would push a balance past the limit of a long throws ArithmeticException, and applyAll changes nothing.

Adding an expense

Group is where the balances live. The map is a LinkedHashMap, so balances come back in the order members joined. Every field that changes is guarded by lock, a private object, and the counters give each expense and payment its id.

group/Group.javalines 22–35 of 164
public final class Group {    /** The largest single expense: $100,000. */    public static final Money MAX_AMOUNT = Money.dollars(100_000);     private final String name;    private final DebtSimplifier simplifier;    // A private lock, so code outside the group cannot hold it.    private final Object lock = new Object();    // Guarded by lock. Members in the order they joined.    private final Map<User, Money> balances = new LinkedHashMap<>();    private final List<Expense> expenses = new ArrayList<>();    private final List<Payment> payments = new ArrayList<>();    private long expenseCounter = 0;    private long paymentCounter = 0;

Adding an expense has three parts: work out the shares, work out how each balance changes, and then change them all at once.

group/Group.javalines 61–92 of 164
    public Expense addExpense(String description, User paidBy, Money amount, SplitRule rule) {        Objects.requireNonNull(description, "description");        Objects.requireNonNull(paidBy, "paidBy");        Objects.requireNonNull(rule, "rule");        requireValidAmount(amount);        // Splitting is pure arithmetic, so it runs before taking the lock.        Map<User, Money> shares = rule.split(amount);         // The payer is owed the whole bill, and each person owes their share.        // In order: the payer first, then the shares in id order.        Map<User, Money> changes = new LinkedHashMap<>();        changes.merge(paidBy, amount, Money::plus);        Money shared = Money.ZERO;        for (Map.Entry<User, Money> share : shares.entrySet()) {            if (share.getValue().isNegative()) {                throw new IllegalStateException("The split rule gave " + share.getKey() + " a negative share");            }            shared = shared.plus(share.getValue());            changes.merge(share.getKey(), share.getValue().negate(), Money::plus);        }        // A rule with a bug could miss the bill, and the balances would stop adding up to zero.        if (!shared.equals(amount)) {            throw new IllegalStateException("The split rule's shares add up to " + shared + ", not " + amount);        }         synchronized (lock) {            applyAll(changes);            Expense expense = new Expense("E-" + (++expenseCounter), description, paidBy, amount, shares);            expenses.add(expense);            return expense;        }    }

Notice three things.

  1. The split happens before the lock (line 67). rule.split is arithmetic on the rule's own data, so there is no reason to make other phones wait while it runs.
  2. The group does not trust the rule (lines 74 to 84). It refuses the expense if any share is negative, or if the shares added up miss the bill. Our three rules never do that, but a rule written next year could, and one bad rule would break the zero-sum rule for every member forever.
  3. The payer comes first. changes is a LinkedHashMap with the payer first and then the shares in id order. If the payer is one of the sharers, merge folds the bill and the payer's own share into one change. Asha paying $900 for four people moves her balance by +$675, not by +$900 and then −$225 in two separate steps.

The balances are written by a small private method:

group/Group.javalines 151–163 of 164
    // Checks and calculates every new balance first, then writes them all.    // A refusal part-way leaves every balance as it was. Called with lock held.    private void applyAll(Map<User, Money> changes) {        Map<User, Money> updated = new HashMap<>();        for (Map.Entry<User, Money> change : changes.entrySet()) {            Money current = balances.get(change.getKey());            if (current == null) {                throw new NotAMemberException(change.getKey(), name);            }            updated.put(change.getKey(), current.plus(change.getValue()));        }        balances.putAll(updated);    }

applyAll first works out every new balance in a separate map, updated. If any name is not a member, it throws NotAMemberException before anything is written. Only when every new value is known does putAll write them. Because the payer comes first in changes, a stranger among the sharers is found after the payer's new balance has been worked out, which is the case this protects against.

A refused expense changes nothing
Asha adds $40 of snacks split with Zoya, who is not in the group. The rule splits the bill into $20 each. The group works out Asha's new balance, finds no balance for Zoya, and throws NotAMemberException. Because applyAll writes nothing until every new balance is known, Asha's balance is still $611.66 and no expense is recorded. Writing Asha's balance as soon as it was worked out would have left her $20 better off for an expense that never happened.Asha adds $40 of snacks split with Zoya, who is not in the group. The rule splits the bill into $20 each. The group works out Asha's new balance, finds no balance for Zoya, and throws NotAMemberException. Because applyAll writes nothing until every new balance is known, Asha's balance is still $611.66 and no expense is recorded. Writing Asha's balance as soon as it was worked out would have left her $20 better off for an expense that never happened.
Every check runs before the first balance is written. Asha adds $40 of snacks split with Zoya, who is not in the group. The rule splits the bill into $20 each. The group works out Asha's new balance, finds no balance for Zoya, and throws NotAMemberException. Because applyAll writes nothing until every new balance is known, Asha's balance is still $611.66 and no expense is recorded. Writing Asha's balance as soon as it was worked out would have left her $20 better off for an expense that never happened.
Decision

Check then write, or write as you go?

Update each balance as it is calculated

This is shorter, and it works for every expense that goes through. But a check that fails half way, such as a name that is not a member, leaves the balances before it changed and the ones after it untouched. The group then holds half an expense, and its balances no longer add up to zero.

Calculate every new balance, then write them allOur pick

A refusal at any point leaves every balance exactly as it was, so "refused" means nothing happened. The cost is one small map per expense, which is a few entries long.

Balances and the plan to settle up

balances() returns a copy, taken under the same lock that writers use. A copy taken under the lock always adds up to zero, because the lock stops a reader from seeing an expense half written. The caller can then sort or display the copy without holding anyone up.

group/Group.javalines 117–127 of 164
    /** A copy of every member's balance, in the order they joined. */    public Map<User, Money> balances() {        synchronized (lock) {            return new LinkedHashMap<>(balances);        }    }     /** A short list of payments that would settle everyone, from this group's simplifier. */    public List<Transfer> simplifiedDebts() {        return simplifier.simplify(balances());    }

A list of balances does not yet tell anyone what to do. After four expenses on a trip, the demo's group stands like this: Asha is owed $611.66, Kabir is owed $165, Ravi owes $398.33 and Meera owes $378.33. Following each expense on its own would mean nine payments between these four people. The group can settle everyone with three.

Nine debts, three payments
On the left are the nine debts the four expenses created, one arrow for each person who shared a bill they did not pay. On the right is the plan worked out from the net balances. Ravi, the biggest debtor, pays Asha, the biggest creditor, $398.33. Meera then pays Asha the $213.33 she is still owed, and Kabir the $165 he is owed. Each payment settles at least one person.On the left are the nine debts the four expenses created, one arrow for each person who shared a bill they did not pay. On the right is the plan worked out from the net balances. Ravi, the biggest debtor, pays Asha, the biggest creditor, $398.33. Meera then pays Asha the $213.33 she is still owed, and Kabir the $165 he is owed. Each payment settles at least one person.
Working from net balances, the plan needs at most one payment fewer than the people involved. On the left are the nine debts the four expenses created, one arrow for each person who shared a bill they did not pay. On the right is the plan worked out from the net balances. Ravi, the biggest debtor, pays Asha, the biggest creditor, $398.33. Meera then pays Asha the $213.33 she is still owed, and Kabir the $165 he is owed. Each payment settles at least one person.

There is more than one way to build that plan, and a group may want a different one, so the plan is a rule of its own.

group/DebtSimplifier.javalines 9–12 of 12
/** Turns net balances, which add up to zero, into payments that settle everyone. */public interface DebtSimplifier {    List<Transfer> simplify(Map<User, Money> balances);}

GreedySimplifier is the one the demo uses. It puts the creditors in one priority queue and the debtors in another, each with the largest amount first.

group/GreedySimplifier.javalines 15–50 of 54
    public List<Transfer> simplify(Map<User, Money> balances) {        Comparator<Party> biggestFirst = Comparator.comparingLong((Party p) -> p.cents).reversed()                .thenComparing(p -> p.user.id());        PriorityQueue<Party> creditors = new PriorityQueue<>(biggestFirst);        PriorityQueue<Party> debtors = new PriorityQueue<>(biggestFirst);         long sum = 0;        for (Map.Entry<User, Money> entry : balances.entrySet()) {            long cents = entry.getValue().cents();            sum = Math.addExact(sum, cents);            if (cents > 0) {                creditors.add(new Party(entry.getKey(), cents));            } else if (cents < 0) {                debtors.add(new Party(entry.getKey(), Math.negateExact(cents)));            }        }        if (sum != 0) {            throw new IllegalArgumentException("Balances must add up to zero, not " + Money.ofCents(sum));        }         List<Transfer> transfers = new ArrayList<>();        while (!creditors.isEmpty() && !debtors.isEmpty()) {            Party creditor = creditors.poll();            Party debtor = debtors.poll();            long amount = Math.min(creditor.cents, debtor.cents);            transfers.add(new Transfer(debtor.user, creditor.user, Money.ofCents(amount)));            // At least one of the two is now settled and leaves the queues for good.            if (creditor.cents > amount) {                creditors.add(new Party(creditor.user, creditor.cents - amount));            }            if (debtor.cents > amount) {                debtors.add(new Party(debtor.user, debtor.cents - amount));            }        }        return transfers;    }

Each round, the biggest debtor pays the biggest creditor as much as one of them needs, Math.min of the two amounts. That settles at least one of the two, who leaves the queues for good. Whoever has money left goes back into their queue. So the loop runs at most once fewer than the number of people with a balance, and with n people that is n − 1 payments at most. Ties between equal amounts go to the lower id, so the plan is the same every time it is asked for. The method also refuses balances that do not add up to zero, since no plan could settle them.

Decision

Greedy, or the fewest payments possible?

Search for the smallest possible number of payments

The true minimum is not always what greedy finds. If Asha is owed $300, Ravi and Meera are owed $200 each, and Kabir owes $400 and Dev $300, greedy uses four payments. Three would do: Dev pays Asha $300, and Kabir pays Ravi and Meera $200 each. Finding the minimum means finding groups of people whose balances cancel out exactly, which means trying combinations of members. The work grows very fast with the size of the group.

Greedy: the biggest debtor pays the biggest creditorOur pick

Greedy takes O(n log n) time, never needs more than n − 1 payments, and is easy to explain and to check. It is not always the minimum: it can use one or more payments too many, as in the example above. If the interviewer asks for the true minimum, explain why it is a search, and that it fits behind DebtSimplifier as a second class.

The plan can ask Meera to pay Kabir, although Meera never shared a bill with Kabir. The amounts are right, but it can surprise people. So whether to simplify should be a choice for each group. Each group is given its own DebtSimplifier, so a group with a different plan needs no change to Group. Not simplifying at all is different: showing the debts expense by expense needs the history, not just the balances. That view sits beside the simplifier, not behind it, and it is a follow-up at the end.

Settling up

When Ravi pays Asha in cash or by UPI, one of them records it in the app:

group/Group.javalines 94–115 of 164
    public Payment settleUp(User from, User to, Money amount) {        Objects.requireNonNull(from, "from");        Objects.requireNonNull(to, "to");        Objects.requireNonNull(amount, "amount");        if (from.equals(to)) {            throw new IllegalArgumentException("A member cannot pay themselves");        }        // No cap: a payment settles a balance, and balances can grow past any one expense.        if (!amount.isPositive()) {            throw new IllegalArgumentException("A payment must be more than zero, not " + amount);        }        // The payer's balance goes up by the amount, and the balance of the one paid goes down.        Map<User, Money> changes = new LinkedHashMap<>();        changes.put(from, amount);        changes.put(to, amount.negate());        synchronized (lock) {            applyAll(changes);            Payment payment = new Payment("P-" + (++paymentCounter), from, to, amount);            payments.add(payment);            return payment;        }    }

settleUp moves Ravi's balance up by the amount and Asha's down by the same amount, through the same applyAll, so a payment to or from a non-member is refused with nothing changed. Paying yourself and paying zero or less are refused before any balance is touched. There is no cap on a payment, so every payment the plan suggests can be recorded. The payment is recorded with an id, like an expense.

Decision

Should a payment bigger than the debt be refused?

Refuse it

It feels safer: Meera owes $378.33, so a payment of $500 looks like a typo. But a payment records money that has already changed hands. If the app refuses it, the app is wrong about the real world, and the group has no way to say what happened.

Record it, and let the balances go past zeroOur pick

If Meera pays Kabir $200 when he is owed $165, Kabir now owes $35, which is exactly true. The next plan includes his $35. The screen can still ask "are you sure?" before sending a payment bigger than the debt, which is a job for the screen and not the group.

Many phones, one group

On a trip, two people can add expenses at the same moment. Both calls run on different threads and both change Asha's balance.

Two expenses, one balance
On the left, there is no lock. Phone A reads Asha's balance as $611.66 and adds $20. Before it writes, phone B reads the same $611.66 and subtracts $10. A writes $631.66, then B writes $601.66, and A's change is lost. On the right, the commit is synchronized, so B waits until A has written. B then reads $631.66 and writes $621.66, and both changes count.On the left, there is no lock. Phone A reads Asha's balance as $611.66 and adds $20. Before it writes, phone B reads the same $611.66 and subtracts $10. A writes $631.66, then B writes $601.66, and A's change is lost. On the right, the commit is synchronized, so B waits until A has written. B then reads $631.66 and writes $621.66, and both changes count.
Without a lock, one phone's change to a balance can overwrite the other's. On the left, there is no lock. Phone A reads Asha's balance as $611.66 and adds $20. Before it writes, phone B reads the same $611.66 and subtracts $10. A writes $631.66, then B writes $601.66, and A's change is lost. On the right, the commit is synchronized, so B waits until A has written. B then reads $631.66 and writes $621.66, and both changes count.

The design guards each group with its own lock, the private lock object. Because nothing outside Group can see it, outside code cannot hold it by accident and stall every phone. addExpense and settleUp take the lock only for the commit, which is a few map lookups and writes. balances takes it to copy one map. expenses and payments copy the whole history under the lock, which takes longer as the history grows. A real app would show the latest expenses a page at a time.

The project includes a check, demo/RaceCheck.java. Eight threads add 2,000 expenses each to one group of four, with random amounts and random people sharing. A ninth thread keeps reading the balances while they run. Each writer also keeps its own record of what its expenses should have done to each balance, so the final balances can be compared:

$ java demo.RaceCheck
16000 expenses added from 8 threads
Balances add up to $0.00
Every balance matches the expenses: true
Snapshots read during the run that did not add up to zero: 0

No expense was lost, every balance matches, and no reader ever saw balances that did not add up to zero. We also ran the same check with the lock removed from addExpense. Runs without the lock lost expenses and left the balances off zero, sometimes by thousands of dollars, and some crashed while copying the expense list. The exact numbers change from run to run and from machine to machine. The bug never shows up when testing with one phone at a time.

Decision

Where does the lock go?

A ConcurrentHashMap of balances, updated with merge

Each merge is safe on its own, so no single balance loses an update. But an expense changes several balances, and between two merges a reader sees the payer credited and the sharers not yet charged. The balances do not add up to zero in that moment, and a failure part way leaves the group with half an expense.

One lock for the whole app

It is correct and simple. But a phone adding an expense to a Goa trip would wait for every other group in the country. Nothing in one group depends on another, so there is no reason to make them wait.

One lock per group, held only for the commitOur pick

The balances of one group are changed together and read together, so one lock per group protects the rule that matters: the balances add up to zero. Different groups never wait for each other, because each lock is private to its group. The arithmetic of the split runs before the lock, so a write holds it only for a few map operations.

The final design

Group is the core. It owns the balances, the expenses, the payments and the lock that guards them. It reaches the rules only through two interfaces: a SplitRule comes with each expense, and the group is given a DebtSimplifier when it is created. A new way to split a bill or to plan payments is a new class, and Group does not change.

The design we built
The classes of the class diagram, laid out the same way, with names only. Group owns Expense and Payment, and uses a SplitRule and a DebtSimplifier. Group carries badges 1, 4, 6 and 7, because it is the one class whose state changes. Money carries badge 2, Proportional carries 3 and GreedySimplifier carries 5. Each number is a row of the table below. SplitRule and DebtSimplifier each carry a purple Strategy tag.The classes of the class diagram, laid out the same way, with names only. Group owns Expense and Payment, and uses a SplitRule and a DebtSimplifier. Group carries badges 1, 4, 6 and 7, because it is the one class whose state changes. Money carries badge 2, Proportional carries 3 and GreedySimplifier carries 5. Each number is a row of the table below. SplitRule and DebtSimplifier each carry a purple Strategy tag.
Each decision has a number, and each number sits on the class where it landed. The classes of the class diagram, laid out the same way, with names only. Group owns Expense and Payment, and uses a SplitRule and a DebtSimplifier. Group carries badges 1, 4, 6 and 7, because it is the one class whose state changes. Money carries badge 2, Proportional carries 3 and GreedySimplifier carries 5. Each number is a row of the table below. SplitRule and DebtSimplifier each carry a purple Strategy tag.
S.No.The questionWhat we choseWhy
1Store who owes whom, or one balance per member?One net balance per memberThe balances always add up to zero, which gives the design one rule to check.
2How should money be stored?A long of cents, inside a small Money recordWhole cents make every sum exact, and equal amounts are always equals.
3Who gets the leftover cents?The largest remainders, ties to the lowest idEach share stays within one cent of its exact value, and the same bill always splits the same way.
4Check then write, or write as you go?Calculate every new balance, then write them allA refused expense leaves every balance exactly as it was.
5Greedy, or the fewest payments possible?Greedy: the biggest debtor pays the biggest creditorIt needs at most n − 1 payments, and the true minimum is a slow search.
6Should a payment bigger than the debt be refused?Record it, and let the balances go past zeroThe payment records money that has already changed hands.
7Where does the lock go?One lock per group, held only for the commitIt keeps each group's balances at zero in total, and groups never wait for each other.

Here is the demo's hotel bill, traced through the final classes:

  1. The app calls addExpense with Asha as the payer, $900 and an EqualSplit of all four members. requireValidAmount checks that the amount is above zero and within MAX_AMOUNT.
  2. Before any lock is taken, addExpense calls rule.split. The split rule runs here: EqualSplit.split calls Proportional.allocate, which gives each person $225.
  3. addExpense builds changes with the payer first, so Asha's +$900 and her own −$225 merge into +$675. It then checks that the shares add up to the bill.
  4. addExpense takes lock and calls applyAll, which works out every new balance and then writes them all with putAll. If a name is not a member, applyAll throws NotAMemberException here, before any balance is written.
  5. Still holding the lock, addExpense records the expense as E-1, adds it to expenses and returns it. The lock is released when the synchronized block ends.

settleUp builds its own changes map, then takes the same lock and calls the same applyAll. So a payment and an expense never change the same balances at the same moment.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

groupGroup.java
package group; import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects; import exception.NotAMemberException;import expense.Expense;import expense.Payment;import money.Money;import split.SplitRule;import user.User; /** * A group of people who share expenses. It keeps one net balance per member: * positive means the group owes them, negative means they owe the group. * The balances always add up to zero. */public final class Group {    /** The largest single expense: $100,000. */    public static final Money MAX_AMOUNT = Money.dollars(100_000);     private final String name;    private final DebtSimplifier simplifier;    // A private lock, so code outside the group cannot hold it.    private final Object lock = new Object();    // Guarded by lock. Members in the order they joined.    private final Map<User, Money> balances = new LinkedHashMap<>();    private final List<Expense> expenses = new ArrayList<>();    private final List<Payment> payments = new ArrayList<>();    private long expenseCounter = 0;    private long paymentCounter = 0;     public Group(String name, List<User> members, DebtSimplifier simplifier) {        this.name = Objects.requireNonNull(name, "name");        this.simplifier = Objects.requireNonNull(simplifier, "simplifier");        if (members.size() < 2) {            throw new IllegalArgumentException("A group needs at least two members");        }        for (User member : members) {            addMember(member);        }    }     public String name() {        return name;    }     public void addMember(User user) {        Objects.requireNonNull(user, "user");        synchronized (lock) {            if (balances.putIfAbsent(user, Money.ZERO) != null) {                throw new IllegalArgumentException(user + " is already in " + name);            }        }    }     public Expense addExpense(String description, User paidBy, Money amount, SplitRule rule) {        Objects.requireNonNull(description, "description");        Objects.requireNonNull(paidBy, "paidBy");        Objects.requireNonNull(rule, "rule");        requireValidAmount(amount);        // Splitting is pure arithmetic, so it runs before taking the lock.        Map<User, Money> shares = rule.split(amount);         // The payer is owed the whole bill, and each person owes their share.        // In order: the payer first, then the shares in id order.        Map<User, Money> changes = new LinkedHashMap<>();        changes.merge(paidBy, amount, Money::plus);        Money shared = Money.ZERO;        for (Map.Entry<User, Money> share : shares.entrySet()) {            if (share.getValue().isNegative()) {                throw new IllegalStateException("The split rule gave " + share.getKey() + " a negative share");            }            shared = shared.plus(share.getValue());            changes.merge(share.getKey(), share.getValue().negate(), Money::plus);        }        // A rule with a bug could miss the bill, and the balances would stop adding up to zero.        if (!shared.equals(amount)) {            throw new IllegalStateException("The split rule's shares add up to " + shared + ", not " + amount);        }         synchronized (lock) {            applyAll(changes);            Expense expense = new Expense("E-" + (++expenseCounter), description, paidBy, amount, shares);            expenses.add(expense);            return expense;        }    }     public Payment settleUp(User from, User to, Money amount) {        Objects.requireNonNull(from, "from");        Objects.requireNonNull(to, "to");        Objects.requireNonNull(amount, "amount");        if (from.equals(to)) {            throw new IllegalArgumentException("A member cannot pay themselves");        }        // No cap: a payment settles a balance, and balances can grow past any one expense.        if (!amount.isPositive()) {            throw new IllegalArgumentException("A payment must be more than zero, not " + amount);        }        // The payer's balance goes up by the amount, and the balance of the one paid goes down.        Map<User, Money> changes = new LinkedHashMap<>();        changes.put(from, amount);        changes.put(to, amount.negate());        synchronized (lock) {            applyAll(changes);            Payment payment = new Payment("P-" + (++paymentCounter), from, to, amount);            payments.add(payment);            return payment;        }    }     /** A copy of every member's balance, in the order they joined. */    public Map<User, Money> balances() {        synchronized (lock) {            return new LinkedHashMap<>(balances);        }    }     /** A short list of payments that would settle everyone, from this group's simplifier. */    public List<Transfer> simplifiedDebts() {        return simplifier.simplify(balances());    }     public List<Expense> expenses() {        synchronized (lock) {            return List.copyOf(expenses);        }    }     public List<Payment> payments() {        synchronized (lock) {            return List.copyOf(payments);        }    }     private static void requireValidAmount(Money amount) {        Objects.requireNonNull(amount, "amount");        if (!amount.isPositive()) {            throw new IllegalArgumentException("An amount must be more than zero, not " + amount);        }        if (amount.compareTo(MAX_AMOUNT) > 0) {            throw new IllegalArgumentException("An amount can be at most " + MAX_AMOUNT + ", not " + amount);        }    }     // Checks and calculates every new balance first, then writes them all.    // A refusal part-way leaves every balance as it was. Called with lock held.    private void applyAll(Map<User, Money> changes) {        Map<User, Money> updated = new HashMap<>();        for (Map.Entry<User, Money> change : changes.entrySet()) {            Money current = balances.get(change.getKey());            if (current == null) {                throw new NotAMemberException(change.getKey(), name);            }            updated.put(change.getKey(), current.plus(change.getValue()));        }        balances.putAll(updated);    }}
Click a class name in the code to open its fileJava · 164 lines · 749 in the project

demo/Main.java runs a trip to Goa for four friends. Asha pays for the hotel, Ravi for dinner, Meera for a cab and Kabir for scuba diving. Two are split equally, one by exact amounts and one by percentage. Then two expenses are refused, the group works out who should pay whom, and Ravi settles up:

$ java demo.Main
E-1 Hotel, $900.00 paid by Asha: {Asha=$225.00, Kabir=$225.00, Meera=$225.00, Ravi=$225.00}
E-2 Dinner, $100.00 paid by Ravi: {Asha=$33.34, Meera=$33.33, Ravi=$33.33}
E-3 Cab, $120.00 paid by Meera: {Asha=$30.00, Kabir=$90.00}
E-4 Scuba, $600.00 paid by Kabir: {Kabir=$120.00, Meera=$240.00, Ravi=$240.00}

Refused: The shares add up to $110.00, not $120.00
Refused: Zoya is not a member of Goa trip
Balances unchanged after both refusals: true

  Asha   is owed $611.66
  Ravi   owes    $398.33
  Meera  owes    $378.33
  Kabir  is owed $165.00
  Total: $0.00
To settle up:
  Ravi pays Asha $398.33
  Meera pays Asha $213.33
  Meera pays Kabir $165.00

Ravi paid Asha $398.33. Now:
  Asha   is owed $213.33
  Ravi   is settled
  Meera  owes    $378.33
  Kabir  is owed $165.00
  Total: $0.00
To settle up:
  Meera pays Asha $213.33
  Meera pays Kabir $165.00

Notice three things in the output. Asha's share of dinner is $33.34 and the others pay $33.33, so the three shares add up to exactly $100. After the two refused expenses, every balance is unchanged. And after Ravi pays Asha $398.33, Ravi is settled and the plan shrinks to Meera's two payments, which are the same two payments as before.

Follow-up questions

After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Split by shares, like 2:1:1."A new ShareSplit that passes the shares to Proportional as weights.Group, the other rules, the simplifier.
"Several people paid one bill."Expense holds a map of payers. addExpense credits each payer instead of one. Its signature changes.The split rules, applyAll, the simplifier.
"Delete or edit an expense."A deleteExpense that applies the opposite of the stored changes through applyAll. Editing is a delete and an add under one lock. Ids come from a counter, not the list size, so a deleted id is never reused.The split rules, Money, the simplifier.
"Show who owes whom without simplifying."Work out the debts from the expenses and payments: one debt per share that is not the payer's own, less what was paid.Balances and the way expenses are added.
"Expenses in dollars and euros."Money gains a currency, and the group keeps one balance per member per currency. The simplifier runs once per currency, or after converting at an agreed rate. One line each in Proportional and ExactSplit, so their results carry the total's currency.How each rule divides a bill.
"A phone retries the same request."Each request carries an id the phone makes up. Group remembers recent ids under its lock and ignores a repeat, so a retried payment after a timeout counts once.The split rules and the simplifier.
"A member wants to leave the group."A removeMember that refuses while their balance is not zero.Everything else.
"Notify members when an expense is added."A listener list on Group, called after the lock is released.The split rules, balances, the simplifier.
"Show a member's total across all groups."A service that adds up their balance in every group they belong to.Each Group.
"Recurring expenses, like monthly rent."A scheduler outside the group that calls addExpense each month.Group and the rules.

In most rows the change lands in a new rule, a new method on Group that reuses applyAll, or a class outside the group.

What the interviewer looks for

Mid-level

A mid-level candidate shows a clear set of classes, a way to add an expense with at least an equal and an exact split, and balances that are correct for simple cases. They use a whole number of cents or a BigDecimal for money, not a double, and they check that exact shares add up to the bill.

Senior

A senior candidate shows everything above and gives the reasons. They store one net balance per member and explain why the balances add up to zero. They put split rules behind an interface, say where the leftover cent goes and why the total is always exact, and refuse a bad expense without changing anything. They name the lock and say what it protects, and they can explain the greedy plan and its n − 1 bound.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They say that greedy is not always the true minimum, and why finding the minimum is a search. They point out that a simplified plan can ask strangers to pay each other, and that a large payment should be recorded rather than refused. They can say how the design would change to keep balances in a database, for example with one transaction per expense.

Common mistakes

  • double for money. Shares that should cancel out leave tiny fractions behind, and "settled" stops meaning zero.
  • Rounding every share and ignoring the gap. $100 three ways becomes $99.99, and the group's balances drift from zero one cent at a time.
  • A table of debts between every pair of members. It grows with the square of the group, and it needs simplifying before it can answer the only question people ask.
  • Changing balances while still checking the expense. A name that fails the check half way leaves the group holding half an expense.
  • A switch on the split type inside Group. Every new way of splitting then means editing the class that also holds the lock and the balances.
  • Claiming that greedy gives the fewest payments. It gives at most n − 1 payments, and not always the minimum.

Summary

  • Ask before designing. The split types, the currency and the number of phones each change the code.
  • Keep money as whole cents in a small Money record, and use exact arithmetic that throws on overflow.
  • Put each way of splitting behind one SplitRule interface, and hand leftover cents to the largest remainders, so shares always add up to the bill.
  • Store one net balance per member. The balances always add up to zero, and that is the rule every method protects.
  • Check everything, calculate every new balance, and only then write them, so a refused expense changes nothing.
  • Turn balances into payments with the greedy plan: at most n − 1 payments, not always the minimum.
  • Guard each group with its own lock, held only for the commit.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.