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
- User and Group (a set of users).
- Expense: who paid, the total, and how much each participant owes. The owed amounts must add up exactly to the total.
- Balance: for each person, the net amount: what they paid minus what they owe, across all expenses. Positive means others owe them.
- Transfer: a suggested payment from one person to another that settles debts.
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
- Who can edit: editing or deleting an expense reverses its old balance changes, then applies the new ones. Keep expenses append-only with a history, so balances can always be recomputed.
- Currencies: balances per currency, or convert at the expense date's rate and store that rate.
- Concurrency: two people adding expenses at once. Updating balances inside a transaction (or recomputing from expenses) keeps them consistent.
Interview checklist
- Model users, groups, expenses, owed amounts and net balances.
- Use integer money, and say how leftover cents are distributed.
- One weighted-split code path, with validation per split type.
- Greedy settlement with two heaps: at most n − 1 transfers, O(n log n).
- Know that the true minimum is NP-hard, and the subset-search alternative.
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.
Do it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (O'Reilly). The friendliest introduction to the classic patterns.
- Refactoring.Guru: design patterns, with diagrams and Java examples for each pattern.
- Joshua Bloch, Effective Java. Idiomatic Java, including builders, immutability and concurrency.