LLD: splitting expenses between friends
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)On a hostel trip Asha pays for the bus, Ravi for the hotel, and everyone wonders who owes whom. The round tests exact money maths, split rules and a small algorithm that turns many debts into a few payments.
Requirements: users, groups, expenses and balances
A net balance is what a user paid minus what they owe: positive means others owe them, negative means they owe.
Four ideas make up the splitter: user, group, expense and balance. This is the scope to agree on.
Group "Goa trip": Asha, Ravi, Meera, JohnExpense: payer, amount (Rs, 2 decimals), participants, split ruleSplits: EQUAL (leftover paise go to the first people) EXACT (amounts must add up to the total) PERCENT (must add up to 100; last person takes rounding leftover)Balance: paid minus owed, per user; all balances add up to 0Settle: suggest a short list of payments that clears every balanceOut: currencies, receipts, notificationsAn expense has a payer, an amount, the people it is shared between and a split rule.
Ask how amounts are split (equally, by exact amounts, by percentage), what happens to a paisa that does not divide evenly, and whether the app should suggest who pays whom at the end. Those three answers decide the whole design.
Split types as strategies
A split strategy is a rule that turns a total and a list of people into each person's share.
First see why money must not be divided with double, then three split rules behind one interface.
Example 1 · Trap: dividing money that does not divide
import java.math.BigDecimal;import java.math.RoundingMode;
public class DivideMoneyDemo { public static void main(String[] args) { BigDecimal total = new BigDecimal("100.00"); BigDecimal three = BigDecimal.valueOf(3);
try { System.out.println(total.divide(three)); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); }
BigDecimal share = total.divide(three, 2, RoundingMode.DOWN); BigDecimal leftover = total.subtract(share.multiply(three)); System.out.println("Share: " + share + ", leftover: " + leftover); System.out.println("First person pays " + share.add(leftover) + ", others pay " + share);
System.out.println("With double: " + (0.1 + 0.2)); }}Error: Non-terminating decimal expansion; no exact representable decimal result. Share: 33.33, leftover: 0.01 First person pays 33.34, others pay 33.33 With double: 0.30000000000000004
What this code does
dividewithout a scale wants an exact answer, and 100 / 3 has none, so it throwsArithmeticException.- Rounding down to 33.33 leaves 1 paisa. Giving it to one person makes the shares add up to exactly 100.00.
- The last line is why money never uses
double: 0.1 + 0.2 is not exactly 0.3.
Example 2 · Equal, exact and percentage splits
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
interface SplitStrategy { Map<String, BigDecimal> split(BigDecimal total, List<String> people);}
class EqualSplit implements SplitStrategy { public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal n = BigDecimal.valueOf(people.size()); BigDecimal share = total.divide(n, 2, RoundingMode.DOWN); int extraPaise = total.subtract(share.multiply(n)).movePointRight(2).intValue(); Map<String, BigDecimal> result = new LinkedHashMap<>(); for (int i = 0; i < people.size(); i++) { result.put(people.get(i), i < extraPaise ? share.add(new BigDecimal("0.01")) : share); } return result; }}
class ExactSplit implements SplitStrategy { private final Map<String, BigDecimal> amounts; ExactSplit(Map<String, BigDecimal> amounts) { this.amounts = amounts; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = amounts.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(total) != 0) { throw new IllegalArgumentException("Exact amounts add up to " + sum + ", not " + total); } Map<String, BigDecimal> result = new LinkedHashMap<>(); for (String p : people) result.put(p, amounts.getOrDefault(p, BigDecimal.ZERO)); return result; }}
class PercentSplit implements SplitStrategy { private final Map<String, BigDecimal> percents; PercentSplit(Map<String, BigDecimal> percents) { this.percents = percents; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = percents.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(new BigDecimal("100")) != 0) { throw new IllegalArgumentException("Percentages add up to " + sum + ", not 100"); } Map<String, BigDecimal> result = new LinkedHashMap<>(); BigDecimal given = BigDecimal.ZERO; for (int i = 0; i < people.size(); i++) { String p = people.get(i); BigDecimal part = i == people.size() - 1 ? total.subtract(given) // last person takes the rounding leftover : total.multiply(percents.get(p)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP); result.put(p, part); given = given.add(part); } return result; }}
public class SplitStrategiesDemo { public static void main(String[] args) { List<String> people = List.of("Asha", "Ravi", "Meera");
SplitStrategy equal = new EqualSplit(); System.out.println("Equal Rs 100.00: " + equal.split(new BigDecimal("100.00"), people));
SplitStrategy exact = new ExactSplit(Map.of("Asha", new BigDecimal("500.00"), "Ravi", new BigDecimal("300.00"), "Meera", new BigDecimal("200.00"))); System.out.println("Exact Rs 1000.00: " + exact.split(new BigDecimal("1000.00"), people));
SplitStrategy percent = new PercentSplit(Map.of("Asha", new BigDecimal("33.33"), "Ravi", new BigDecimal("33.33"), "Meera", new BigDecimal("33.34"))); System.out.println("Percent Rs 999.00: " + percent.split(new BigDecimal("999.00"), people)); }}Equal Rs 100.00: {Asha=33.34, Ravi=33.33, Meera=33.33}
Exact Rs 1000.00: {Asha=500.00, Ravi=300.00, Meera=200.00}
Percent Rs 999.00: {Asha=332.97, Ravi=332.97, Meera=333.06}What this code does
- All three rules return the same kind of answer, a map from person to share, so the group code never needs to know which rule an expense used.
- Equal split gives the leftover paisa to Asha, the first person, so 33.34 + 33.33 + 33.33 = 100.00.
- For percentages, rounding each share would give 999.01 here, so the last person takes whatever is left (333.06) and the total stays exact.
Equal, exact and percentage splits do the same job in different ways, so they implement one SplitStrategy interface, and an expense just holds the rule it was created with.
Money uses BigDecimal, Java's exact decimal type, with 2 decimal places, because double cannot store values like 0.10 exactly. BigDecimal also makes you decide rounding: divide(n, 2, RoundingMode.DOWN) gives 33.33 for Rs 100 between three, and the leftover paisa goes to the first person.
Fix the error
Fix the BigDecimal line
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
The total of a bill must be stored exactly.
Error
Fix1.java:5: error: incompatible types: double cannot be converted to BigDecimal
BigDecimal total = 100.50;
^Validating splits that do not add up
Split validation checks the user's numbers before the expense is saved: exact amounts must add up to the total, and percentages must add up to 100.
BigDecimal values must be compared with compareTo, not equals. This short program shows why.
import java.math.BigDecimal;
public class CompareMoneyDemo { public static void main(String[] args) { BigDecimal a = new BigDecimal("100.0"); BigDecimal b = new BigDecimal("100.00"); System.out.println("equals: " + a.equals(b)); System.out.println("compareTo: " + a.compareTo(b)); }}equals: false compareTo: 0
Example 3 · Rejecting splits that do not add up
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
interface SplitStrategy { Map<String, BigDecimal> split(BigDecimal total, List<String> people);}
class EqualSplit implements SplitStrategy { public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal n = BigDecimal.valueOf(people.size()); BigDecimal share = total.divide(n, 2, RoundingMode.DOWN); int extraPaise = total.subtract(share.multiply(n)).movePointRight(2).intValue(); Map<String, BigDecimal> result = new LinkedHashMap<>(); for (int i = 0; i < people.size(); i++) { result.put(people.get(i), i < extraPaise ? share.add(new BigDecimal("0.01")) : share); } return result; }}
class ExactSplit implements SplitStrategy { private final Map<String, BigDecimal> amounts; ExactSplit(Map<String, BigDecimal> amounts) { this.amounts = amounts; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = amounts.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(total) != 0) { throw new IllegalArgumentException("Exact amounts add up to " + sum + ", not " + total); } Map<String, BigDecimal> result = new LinkedHashMap<>(); for (String p : people) result.put(p, amounts.getOrDefault(p, BigDecimal.ZERO)); return result; }}
class PercentSplit implements SplitStrategy { private final Map<String, BigDecimal> percents; PercentSplit(Map<String, BigDecimal> percents) { this.percents = percents; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = percents.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(new BigDecimal("100")) != 0) { throw new IllegalArgumentException("Percentages add up to " + sum + ", not 100"); } Map<String, BigDecimal> result = new LinkedHashMap<>(); BigDecimal given = BigDecimal.ZERO; for (int i = 0; i < people.size(); i++) { String p = people.get(i); BigDecimal part = i == people.size() - 1 ? total.subtract(given) // last person takes the rounding leftover : total.multiply(percents.get(p)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP); result.put(p, part); given = given.add(part); } return result; }}
public class SplitValidationDemo { static void tryIt(String label, SplitStrategy rule, String total, List<String> people) { try { System.out.println(label + ": " + rule.split(new BigDecimal(total), people)); } catch (IllegalArgumentException e) { System.out.println(label + ": rejected, " + e.getMessage()); } }
public static void main(String[] args) { List<String> people = List.of("Asha", "Ravi"); tryIt("Exact 600", new ExactSplit(Map.of("Asha", new BigDecimal("400.00"), "Ravi", new BigDecimal("150.00"))), "600.00", people); tryIt("Percent", new PercentSplit(Map.of("Asha", new BigDecimal("60"), "Ravi", new BigDecimal("30"))), "600.00", people); tryIt("Exact 550", new ExactSplit(Map.of("Asha", new BigDecimal("400.0"), "Ravi", new BigDecimal("150.00"))), "550.00", people); }}Exact 600: rejected, Exact amounts add up to 550.00, not 600.00
Percent: rejected, Percentages add up to 90, not 100
Exact 550: {Asha=400.0, Ravi=150.00}What this code does
- Exact amounts of 400 + 150 cannot pay for a Rs 600 hotel bill, so the split is rejected with the real sum in the message.
- Percentages of 60 + 30 leave 10% unpaid, which is also rejected before anything is saved.
- The last case passes even though
400.0has one decimal place:compareTocompares values, so 550.00 and 550.00 match.
If the numbers do not add up, throw an IllegalArgumentException with a message that says what they add up to.
equals also compares the scale, so 100.0 and 100.00 are "not equal", while compareTo returns 0 for the same value.
Simplifying debts into fewer payments
A greedy rule takes the best-looking step at each moment. Here, the person who owes the most pays the person who is owed the most.
Debts become payments in two steps: net balances first, then the greedy rule.
Example 4 · Simplifying debts with the greedy rule
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
record Debt(String from, String to, BigDecimal amount) { }
public class SimplifyDebtsDemo { static List<String> simplify(Map<String, BigDecimal> net) { Map<String, BigDecimal> bal = new TreeMap<>(net); List<String> payments = new ArrayList<>(); while (true) { Optional<Map.Entry<String, BigDecimal>> creditor = bal.entrySet().stream() .filter(e -> e.getValue().signum() > 0).max(Map.Entry.comparingByValue()); Optional<Map.Entry<String, BigDecimal>> debtor = bal.entrySet().stream() .filter(e -> e.getValue().signum() < 0).min(Map.Entry.comparingByValue()); if (creditor.isEmpty() || debtor.isEmpty()) break; String to = creditor.get().getKey(); String from = debtor.get().getKey(); BigDecimal amount = creditor.get().getValue().min(debtor.get().getValue().negate()); payments.add(from + " pays " + to + " Rs " + amount); bal.put(to, bal.get(to).subtract(amount)); bal.put(from, bal.get(from).add(amount)); } return payments; }
public static void main(String[] args) { List<Debt> debts = List.of( new Debt("Ravi", "Asha", new BigDecimal("300.00")), new Debt("Asha", "Meera", new BigDecimal("300.00")), new Debt("John", "Ravi", new BigDecimal("200.00")), new Debt("Meera", "John", new BigDecimal("50.00")));
Map<String, BigDecimal> net = new TreeMap<>(); for (Debt d : debts) { net.merge(d.to(), d.amount(), BigDecimal::add); net.merge(d.from(), d.amount().negate(), BigDecimal::add); } System.out.println("Debts: " + debts.size() + ", net: " + net); simplify(net).forEach(System.out::println); }}Debts: 4, net: {Asha=0.00, John=-150.00, Meera=250.00, Ravi=-100.00}
John pays Meera Rs 150.00
Ravi pays Meera Rs 100.00What this code does
- Four debts turn into net balances first. Asha both owes and is owed Rs 300, so her net is zero and she drops out.
- Each round, the biggest debtor pays the biggest creditor; one of them reaches zero, so the loop always ends.
- The result is 2 payments instead of 4, and each person pays or receives exactly their net amount.
Debt simplification replaces a tangle of "A owes B, B owes C" with a short list of payments that leaves everyone at zero. Who owed whom no longer matters, only how much each person is up or down.
The payment is as much as one of the two needs, so one of them reaches zero every time, and a group of n people needs at most n - 1 payments. Greedy usually gives few payments; the guaranteed fewest is a much harder problem, and interviewers accept the greedy answer.
Order of execution
Settle the debts
Put the greedy steps in order.
Single-file design with BigDecimal amounts
Scale is the number of decimal places in a BigDecimal. Money uses scale 2, such as 100.00.
One expense of each split type, then the balances, a zero-sum check and the suggested payments.
Example 5 · The expense splitter in one file
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.TreeMap;
interface SplitStrategy { Map<String, BigDecimal> split(BigDecimal total, List<String> people);}
class EqualSplit implements SplitStrategy { public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal n = BigDecimal.valueOf(people.size()); BigDecimal share = total.divide(n, 2, RoundingMode.DOWN); int extraPaise = total.subtract(share.multiply(n)).movePointRight(2).intValue(); Map<String, BigDecimal> result = new LinkedHashMap<>(); for (int i = 0; i < people.size(); i++) { result.put(people.get(i), i < extraPaise ? share.add(new BigDecimal("0.01")) : share); } return result; }}
class ExactSplit implements SplitStrategy { private final Map<String, BigDecimal> amounts; ExactSplit(Map<String, BigDecimal> amounts) { this.amounts = amounts; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = amounts.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(total) != 0) { throw new IllegalArgumentException("Exact amounts add up to " + sum + ", not " + total); } Map<String, BigDecimal> result = new LinkedHashMap<>(); for (String p : people) result.put(p, amounts.getOrDefault(p, BigDecimal.ZERO)); return result; }}
class PercentSplit implements SplitStrategy { private final Map<String, BigDecimal> percents; PercentSplit(Map<String, BigDecimal> percents) { this.percents = percents; }
public Map<String, BigDecimal> split(BigDecimal total, List<String> people) { BigDecimal sum = percents.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); if (sum.compareTo(new BigDecimal("100")) != 0) { throw new IllegalArgumentException("Percentages add up to " + sum + ", not 100"); } Map<String, BigDecimal> result = new LinkedHashMap<>(); BigDecimal given = BigDecimal.ZERO; for (int i = 0; i < people.size(); i++) { String p = people.get(i); BigDecimal part = i == people.size() - 1 ? total.subtract(given) // last person takes the rounding leftover : total.multiply(percents.get(p)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP); result.put(p, part); given = given.add(part); } return result; }}
record Expense(String title, String paidBy, BigDecimal amount, List<String> participants, SplitStrategy rule) { }
class Group { private final String name; private final Map<String, BigDecimal> net = new TreeMap<>();
Group(String name, List<String> members) { this.name = name; for (String m : members) net.put(m, new BigDecimal("0.00")); }
void add(Expense e) { Map<String, BigDecimal> shares = e.rule().split(e.amount(), e.participants()); // validates first net.merge(e.paidBy(), e.amount(), BigDecimal::add); shares.forEach((person, share) -> net.merge(person, share.negate(), BigDecimal::add)); System.out.println(e.title() + " Rs " + e.amount() + " paid by " + e.paidBy() + ": " + shares); }
Map<String, BigDecimal> balances() { return new TreeMap<>(net); }
static List<String> simplify(Map<String, BigDecimal> net) { Map<String, BigDecimal> bal = new TreeMap<>(net); List<String> payments = new ArrayList<>(); while (true) { Optional<Map.Entry<String, BigDecimal>> creditor = bal.entrySet().stream() .filter(e -> e.getValue().signum() > 0).max(Map.Entry.comparingByValue()); Optional<Map.Entry<String, BigDecimal>> debtor = bal.entrySet().stream() .filter(e -> e.getValue().signum() < 0).min(Map.Entry.comparingByValue()); if (creditor.isEmpty() || debtor.isEmpty()) break; String to = creditor.get().getKey(); String from = debtor.get().getKey(); BigDecimal amount = creditor.get().getValue().min(debtor.get().getValue().negate()); payments.add(from + " pays " + to + " Rs " + amount); bal.put(to, bal.get(to).subtract(amount)); bal.put(from, bal.get(from).add(amount)); } return payments; }}
public class ExpenseSplitterDemo { public static void main(String[] args) { List<String> all = List.of("Asha", "John", "Meera", "Ravi"); Group goa = new Group("Goa trip", all);
goa.add(new Expense("Hotel", "Asha", new BigDecimal("1000.00"), List.of("Asha", "John", "Meera"), new EqualSplit())); goa.add(new Expense("Cab", "Ravi", new BigDecimal("900.00"), List.of("John", "Meera", "Ravi"), new ExactSplit(Map.of("John", new BigDecimal("400.00"), "Meera", new BigDecimal("200.00"), "Ravi", new BigDecimal("300.00"))))); goa.add(new Expense("Hotel", "Meera", new BigDecimal("4000.00"), all, new PercentSplit(Map.of("Asha", new BigDecimal("30"), "John", new BigDecimal("30"), "Meera", new BigDecimal("20"), "Ravi", new BigDecimal("20"))))); try { goa.add(new Expense("Taxi", "John", new BigDecimal("300.00"), List.of("John", "Ravi"), new ExactSplit(Map.of("John", new BigDecimal("100.00"), "Ravi", new BigDecimal("100.00"))))); } catch (IllegalArgumentException ex) { System.out.println("Taxi rejected: " + ex.getMessage()); }
Map<String, BigDecimal> balances = goa.balances(); System.out.println("Balances: " + balances); System.out.println("Sum: " + balances.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add)); Group.simplify(balances).forEach(System.out::println); }}Hotel Rs 1000.00 paid by Asha: {Asha=333.34, John=333.33, Meera=333.33}
Cab Rs 900.00 paid by Ravi: {John=400.00, Meera=200.00, Ravi=300.00}
Hotel Rs 4000.00 paid by Meera: {Asha=1200.00, John=1200.00, Meera=800.00, Ravi=800.00}
Taxi rejected: Exact amounts add up to 200.00, not 300.00
Balances: {Asha=-533.34, John=-1933.33, Meera=2666.67, Ravi=-200.00}
Sum: 0.00
John pays Meera Rs 1933.33
Asha pays Meera Rs 533.34
Ravi pays Meera Rs 200.00What this code does
Group.addasks the expense's rule for the shares first, so a bad split throws before any balance changes: the rejected snacks leave no trace.- Each expense adds the full amount to the payer and subtracts each share from its person; the balances add up to exactly 0.00.
- Settlement runs on the final net balances, so the order in which expenses were added does not matter.
The single-file design has SplitStrategy with three implementations, an Expense record, and a Group that adds expenses, keeps net balances and suggests settlements. Every amount is a BigDecimal with scale 2.
The demo prints the balances and checks that they add up to zero: a quick way to catch a rounding bug.
Next step
Check your understanding
12 quick questions