LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 4 OF 42

Design Splitwise: Expense Sharing Low-Level Design in Java

An expense sharing app designed and coded: requirements, users, groups, expenses and shares, why one net balance per user beats a pairwise ledger, equal, exact and percentage splits as Strategies chosen by a Factory, rounding without losing a paisa, debt simplification with two heaps, settling up, a lock per group, Observer notifications and the follow-ups, with full Java 17 code.

Patterns usedStrategyObserverFactory method

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 226 lines, with a small main() demo. Save it as Splitwise.java, then run javac Splitwise.java && java Splitwise.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Expense sharing: users add expenses split equally, by exact amounts or by percentages; the service keeps
 * one net balance per user per group and can simplify the debts to the fewest payments.
 * Money is held in paise (long), never in double.
 */
public class Splitwise {

    // ---------- the model ----------
    record User(String id, String name) {}

    enum SplitType { EQUAL, EXACT, PERCENT }

    /** What one participant owes for an expense, in paise. */
    record Share(User user, long amount) {}

    record Expense(long id, String groupId, String note, User paidBy, long amount, List<Share> shares) {}

    record Payment(User from, User to, long amount) {
        @Override
        public String toString() { return from.name() + " pays " + to.name() + " " + rupees(amount); }
    }

    static final class Group {
        final String id;
        final String name;
        final List<User> members;
        final List<Expense> expenses = new ArrayList<>();
        /** Net balance per user: positive = is owed money, negative = owes money. Always sums to zero. */
        final Map<User, Long> net = new LinkedHashMap<>();

        Group(String id, String name, List<User> members) {
            this.id = id;
            this.name = name;
            this.members = List.copyOf(members);
            for (User u : members) net.put(u, 0L);
        }
    }

    // ---------- Strategy + Factory for splits ----------
    interface SplitStrategy {
        /** values: ignored for EQUAL, paise for EXACT, percentages for PERCENT. */
        List<Share> split(long amount, List<User> users, List<Double> values);
    }

    static final class EqualSplit implements SplitStrategy {
        public List<Share> split(long amount, List<User> users, List<Double> values) {
            long base = amount / users.size(), extra = amount % users.size();
            List<Share> out = new ArrayList<>();
            for (int i = 0; i < users.size(); i++)
                out.add(new Share(users.get(i), base + (i < extra ? 1 : 0)));
            return out; // 100 split 3 ways = 34, 33, 33: no paisa is lost
        }
    }

    static final class ExactSplit implements SplitStrategy {
        public List<Share> split(long amount, List<User> users, List<Double> values) {
            if (values.size() != users.size()) throw new IllegalArgumentException("One amount per user");
            long sum = 0;
            List<Share> out = new ArrayList<>();
            for (int i = 0; i < users.size(); i++) {
                long v = Math.round(values.get(i));
                sum += v;
                out.add(new Share(users.get(i), v));
            }
            if (sum != amount)
                throw new IllegalArgumentException("Exact amounts add to " + sum + ", not " + amount);
            return out;
        }
    }

    static final class PercentSplit implements SplitStrategy {
        public List<Share> split(long amount, List<User> users, List<Double> values) {
            if (values.size() != users.size()) throw new IllegalArgumentException("One percentage per user");
            double total = values.stream().mapToDouble(Double::doubleValue).sum();
            if (Math.abs(total - 100.0) > 1e-9)
                throw new IllegalArgumentException("Percentages add to " + total);
            List<Share> out = new ArrayList<>();
            long given = 0;
            for (int i = 0; i < users.size(); i++) {
                long v = i == users.size() - 1 ? amount - given : Math.round(amount * values.get(i) / 100.0);
                given += v;
                out.add(new Share(users.get(i), v)); // the last person absorbs the rounding
            }
            return out;
        }
    }

    static SplitStrategy splitFor(SplitType type) {
        return switch (type) {
            case EQUAL -> new EqualSplit();
            case EXACT -> new ExactSplit();
            case PERCENT -> new PercentSplit();
        };
    }

    /** Observer: email, push or an activity feed hears about every expense. */
    interface ExpenseListener { void onExpense(Group g, Expense e); }

    // ---------- the service ----------
    private final Map<String, Group> groups = new ConcurrentHashMap<>();
    private final List<ExpenseListener> listeners = new CopyOnWriteArrayList<>();
    private final AtomicLong expenseSeq = new AtomicLong();

    Group createGroup(String id, String name, List<User> members) {
        Group g = new Group(id, name, members);
        if (groups.putIfAbsent(id, g) != null) throw new IllegalArgumentException("Group exists: " + id);
        return g;
    }

    void subscribe(ExpenseListener l) { listeners.add(l); }

    Expense addExpense(String groupId, String note, User paidBy, long amount, SplitType type,
                       List<User> among, List<Double> values) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        Group g = group(groupId);
        List<Share> shares = splitFor(type).split(amount, among, values);
        Expense e;
        synchronized (g) { // one lock per group: groups never block each other
            List<User> involved = new ArrayList<>(among);
            involved.add(paidBy);
            for (User u : involved)
                if (!g.members.contains(u))
                    throw new IllegalArgumentException(u.name() + " is not in " + g.name);
            e = new Expense(expenseSeq.incrementAndGet(), groupId, note, paidBy, amount, List.copyOf(shares));
            g.expenses.add(e);
            g.net.merge(paidBy, amount, Long::sum);
            for (Share s : shares) g.net.merge(s.user(), -s.amount(), Long::sum);
        }
        for (ExpenseListener l : listeners) l.onExpense(g, e);
        return e;
    }

    /** Record a real-world payment between two members (settling up). */
    void settle(String groupId, User from, User to, long amount) {
        Group g = group(groupId);
        synchronized (g) {
            g.net.merge(from, amount, Long::sum);
            g.net.merge(to, -amount, Long::sum);
        }
    }

    Map<User, Long> balances(String groupId) {
        Group g = group(groupId);
        synchronized (g) { return new LinkedHashMap<>(g.net); }
    }

    /**
     * Greedy debt simplification: repeatedly match the biggest debtor with the biggest creditor.
     * At most n - 1 payments, because every payment settles at least one person fully.
     */
    List<Payment> simplify(String groupId) {
        Comparator<Map.Entry<User, Long>> bigFirst =
                (a, b) -> Long.compare(Math.abs(b.getValue()), Math.abs(a.getValue()));
        PriorityQueue<Map.Entry<User, Long>> owed = new PriorityQueue<>(bigFirst);
        PriorityQueue<Map.Entry<User, Long>> owes = new PriorityQueue<>(bigFirst);
        for (Map.Entry<User, Long> e : balances(groupId).entrySet()) {
            if (e.getValue() > 0) owed.add(Map.entry(e.getKey(), e.getValue()));
            else if (e.getValue() < 0) owes.add(Map.entry(e.getKey(), e.getValue()));
        }
        List<Payment> plan = new ArrayList<>();
        while (!owed.isEmpty() && !owes.isEmpty()) {
            Map.Entry<User, Long> c = owed.poll(), d = owes.poll();
            long pay = Math.min(c.getValue(), -d.getValue());
            plan.add(new Payment(d.getKey(), c.getKey(), pay));
            if (c.getValue() - pay > 0) owed.add(Map.entry(c.getKey(), c.getValue() - pay));
            if (d.getValue() + pay < 0) owes.add(Map.entry(d.getKey(), d.getValue() + pay));
        }
        return plan;
    }

    private Group group(String id) {
        Group g = groups.get(id);
        if (g == null) throw new IllegalArgumentException("No group " + id);
        return g;
    }

    static String rupees(long paise) { return String.format("%d.%02d", paise / 100, Math.abs(paise % 100)); }

    // ---------- demo ----------
    public static void main(String[] args) {
        User planner = new User("u1", "Planner"), driver = new User("u2", "Driver");
        User chef = new User("u3", "Chef"), guest = new User("u4", "Guest");
        List<User> all = List.of(planner, driver, chef, guest);
        Splitwise app = new Splitwise();
        app.subscribe((g, e) -> System.out.println("  [feed] " + e.paidBy().name() + " added '"
                + e.note() + "' " + rupees(e.amount()) + " in " + g.name));
        app.createGroup("goa", "Goa trip", all);

        app.addExpense("goa", "Villa", planner, 1_200_000, SplitType.EQUAL, all, List.of());
        app.addExpense("goa", "Dinners", driver, 900_000, SplitType.EXACT, all,
                List.of(300_000.0, 150_000.0, 250_000.0, 200_000.0));
        app.addExpense("goa", "Scooters", chef, 100_000, SplitType.PERCENT, List.of(driver, chef, guest),
                List.of(50.0, 25.0, 25.0));
        app.addExpense("goa", "Snacks", guest, 10_000, SplitType.EQUAL, List.of(planner, driver, chef),
                List.of());

        Map<User, Long> net = app.balances("goa");
        net.forEach((u, v) -> System.out.println(u.name() + ": " + (v >= 0 ? "gets " : "owes ")
                + rupees(Math.abs(v))));
        if (net.values().stream().mapToLong(Long::longValue).sum() != 0)
            throw new AssertionError("money leaked");

        List<Payment> plan = app.simplify("goa");
        System.out.println("Settle up in " + plan.size() + " payments:");
        plan.forEach(p -> System.out.println("  " + p));
        Map<User, Long> after = new HashMap<>(net);
        for (Payment p : plan) {
            app.settle("goa", p.from(), p.to(), p.amount());
            after.merge(p.from(), p.amount(), Long::sum);
            after.merge(p.to(), -p.amount(), Long::sum);
        }
        if (after.values().stream().anyMatch(v -> v != 0)) throw new AssertionError("not settled");
        System.out.println("After settling: " + app.simplify("goa").size() + " payments left");
    }
}

Notes

Requirements

The requirements. Users belong to groups. Anyone can add an expense: who paid, how much, and how it is split among which members, equally, by exact amounts or by percentages. The app shows what each person owes or is owed, suggests a short list of payments that settles everything, records those payments when they happen, and notifies the group about new expenses.

Clarify the money rules first, because they decide the data types. One currency per group for now. When a hundred rupees is split three ways, someone pays thirty-four and the others thirty-three; the total must always match exactly. Exact amounts must add up to the bill, and percentages to a hundred, or the expense is rejected. The payer and everyone in the split must be group members.

Requirements
  • users and groups of users
  • add an expense: who paid,
  • how much, split among whom
  • splits: equal, exact amounts,
  • or percentages
  • show what each person owes
  • or is owed
  • simplify: fewest payments
  • record a settle-up payment
  • notify members of new expenses
Clarify first
  • one currency per group?
  • yes, multi-currency later
  • rounding: 100 split 3 ways?
  • 34, 33, 33: never lose 1
  • must splits add up exactly?
  • yes, reject otherwise
  • payer must be in the group?
  • yes
  • edit or delete expenses?
  • version two

Entities

The entities. The service holds groups. A group has members, a list of expenses, and a running balance per member. An expense records who paid, the total, a note, and its shares, where each share says one user owes one amount. Users are plain records. Everything except the group is immutable once created, which matters later for thread safety and for keeping an honest history.

Class diagram

In code, almost everything is a record. A user, a share, an expense and a suggested payment never change after creation. Amounts are whole paise stored in a long. Never use double for money: binary floating point cannot represent most decimal amounts, and small errors add up across hundreds of expenses until the balances no longer sum to zero.

Records
record User(String id, String name)
enum SplitType { EQUAL, EXACT, PERCENT }
record Share(User user, long amount)
record Expense(long id, String groupId,
    String note, User paidBy,
    long amount, List<Share> shares)
record Payment(User from, User to,
    long amount)

amounts are paise: 12000.00 = 1200000

Net balances

A key design choice: how to store who owes what. A pairwise ledger, a cell for every pair of users, grows with the square of the group and still needs simplifying at the end. Instead keep one signed number per user: positive means they are owed, negative means they owe. Adding an expense credits the payer the full amount and debits each share. The numbers always sum to zero, which is a free correctness check.

Net balance per user
  • positive: is owed money
  • negative: owes money
  • sum over the group is always 0
  • add expense:
  • net[payer] += amount
  • net[each share] -= share
  • pairwise ledger: N x N cells,
  • and still needs simplifying

Strategy and Factory

Each way of splitting is a Strategy: one interface that turns an amount and a list of users into shares, with equal, exact and percent implementations. Each class also validates its own input: exact amounts must add up, percentages must total a hundred. A small factory method maps the split type to the right strategy, so the service never contains a chain of if statements. Adding shares by weight later is one more class and one more case.

SplitStrategy
interface SplitStrategy {
  List<Share> split(long amount,
      List<User> users, List<Double> v);
}
static SplitStrategy splitFor(SplitType t) {
  return switch (t) {
    case EQUAL -> new EqualSplit();
    case EXACT -> new ExactSplit();
    case PERCENT -> new PercentSplit();
  };
}

Rounding

Rounding is where weak answers lose money. For an equal split, integer division gives the base share and the remainder is a few leftover paise; give one extra paisa to the first few people. A hundred among three becomes thirty-four, thirty-three, thirty-three. For percentages, round each share but give the last person whatever is left, so the total always matches. Interviewers often test exactly this case.

No paisa lost
equal: 100 among 3
  base = 100 / 3 = 33, extra = 1
  shares: 34, 33, 33

percent: last person gets
  amount - sum(others)
  so rounding never drifts

exact: sum != amount -> reject

Flow: add an expense

The add-expense flow. Compute the shares first, outside any lock, because it only reads the arguments. Then lock this one group, check that the payer and everyone in the split are members, append the expense, credit the payer and debit each share. Release the lock, then notify listeners. Notifying outside the lock means a slow email sender can never block someone else adding an expense.

Here is the demo in the code. The planner pays twelve thousand for a villa split equally among four. The driver pays nine thousand for dinners with exact shares. The chef pays a thousand for scooters split fifty, twenty-five, twenty-five among three. The guest buys snacks for a hundred. The planner is owed about five thousand nine hundred and sixty-seven, the driver three thousand nine hundred and sixty-seven, and the other two owe. The total is exactly zero.

addExpense(...)
shares = splitFor(type).split(..)
synchronized (group) {
  check payer and users are members
  expenses.add(expense)
  net[payer] += amount
  for (s : shares) net[s.user] -= s.amt
}
for (l : listeners) l.onExpense(g, e)
A worked example
  • Planner pays villa 12,000
  • equal among 4
  • Driver pays dinners 9,000
  • exact: 3k, 1.5k, 2.5k, 2k
  • Chef pays scooters 1,000
  • 50/25/25 among 3
  • Guest pays snacks 100
  • Planner +5,966.66
  • Driver +3,966.67
  • Chef -4,783.33 Guest -5,150

Simplify debts

Simplifying debts uses the net balances directly. Put creditors in one max-heap and debtors in another. Repeatedly take the biggest of each, make a payment of the smaller of the two amounts, and push back whoever still has a balance. Every payment fully settles at least one person, so a group of n people needs at most n minus one payments. Our example settles in three.

Is greedy the minimum? Not always. The true minimum comes from splitting people into as many groups as possible whose balances sum to zero, and that is a hard problem in general. For small groups, under about fifteen people, a bitmask dynamic programming search finds the exact minimum. For anything bigger, the greedy answer with at most n minus one payments is what real apps use. Saying this unprompted scores well.

simplify()
owed = max-heap of creditors
owes = max-heap of debtors
while both non-empty:
  c = owed.poll(); d = owes.poll()
  pay = min(c.amount, -d.amount)
  plan.add(d pays c, pay)
  push back whoever is not settled

every payment settles someone:
  at most n - 1 payments
Is it optimal?
  • greedy: at most n - 1 payments
  • true minimum: split people into
  • the most groups that each sum
  • to zero, then n - groups
  • that is NP-hard in general
  • small groups (under ~15):
  • bitmask DP finds the minimum
  • otherwise: greedy is the norm

Settle up

Settling up is simple with net balances. When the guest pays the planner five thousand one hundred and fifty, add that amount to the guest's balance and subtract it from the planner's, under the group lock. After all three suggested payments, every balance is exactly zero and simplify returns an empty plan, which the demo asserts. Storing it as a payment record also keeps a clear history.

Concurrency

Concurrency. Two friends may add expenses to the same group at the same moment, and the balance updates must not interleave. Lock the smallest thing that has to change together, which is one group. Groups live in a concurrent map, and different groups never block each other. Split maths happens before the lock, notifications after it, and balance reads return a copy so callers never see a half-updated map.

Thread safety
  • groups: ConcurrentHashMap
  • lock per group: synchronized(g)
  • two groups never block
  • split math outside the lock
  • listeners called after unlock
  • balances() returns a copy
  • expense ids: AtomicLong
  • records: immutable, shareable

Observer

Notifications are the Observer pattern. An activity feed, an email digest and push notifications each register an expense listener. The service calls them after the lock is released, so slow or failing channels cannot hold up anyone's balance. Adding a new channel, like a weekly summary, is a new listener and no change to the expense code.

Extensibility

Extensions. Editing or deleting an expense should append a reversing entry instead of rewriting history, so balances can always be rebuilt and audited. Shares by weight is a new strategy. Multiple currencies convert at the rate on the expense date. Recurring rent is a scheduler that adds an expense each month. In a database, the expense ledger is the source of truth and balances are a cache of it.

Extension points
  • edit or delete: append a
  • reversing entry, keep history
  • shares by weight: new strategy
  • multi-currency: convert at the
  • rate on the expense date
  • recurring rent: a scheduler
  • adds expenses monthly
  • storage: append-only ledger,
  • balances are a cache of it

Follow-ups

Expect follow-ups. Why not double for money? Rounding drift. Why at most n minus one payments? Each one settles at least one person. Is the true minimum easy? No, it is hard in general, so use bitmask search only for small groups. Two people editing the same expense? Use a version number and reject stale updates. And a one-off expense between two friends is just a two-person group, so no special case is needed.

Follow-ups to expect
  • why not double for money?
  • how do you avoid lost paise?
  • n - 1 payments: prove it
  • minimum payments: complexity?
  • two users edit the same
  • expense? version numbers
  • balances drift after a bug?
  • rebuild from the ledger
  • non-group expenses?
  • a two-person group

Say it like this

The short version. Expenses are immutable records with shares in paise. Split rules are strategies chosen by a factory, and they always add up exactly. Each group keeps one net balance per user, updated under that group's own lock. Two heaps simplify the debts into at most n minus one payments, and notifications are observers called outside the lock.

In the interview
  • "Expenses are immutable records
  • with shares in paise. Splits
  • are strategies from a factory
  • and always add up exactly. A
  • group keeps one net balance per
  • user under its own lock. Two
  • heaps simplify debts in at most
  • n - 1 payments."

Interview questions

Why keep one net balance per user instead of a who-owes-whom table?

A pairwise table grows with the square of the group and still needs simplifying. One signed number per user is enough to compute who should pay whom, is cheap to update, and must always sum to zero, which is a built-in correctness check.

How do you model the different split types?

Strategy pattern: a SplitStrategy interface with EqualSplit, ExactSplit and PercentSplit, each validating its own input. A factory method maps the SplitType enum to a strategy, so a new rule such as shares by weight is one new class.

How do you make sure no money is lost to rounding?

Store paise in a long. For equal splits give the remainder one paisa at a time to the first participants; for percentages let the last participant take amount minus the others. The shares then always sum to the expense.

How does debt simplification work?

Put creditors and debtors in two max-heaps, repeatedly match the largest of each for the smaller of their amounts, and push back any remainder. Each payment settles at least one person, so there are at most n - 1 payments.

Is the greedy simplification optimal?

Not always. The exact minimum requires partitioning users into the maximum number of zero-sum subsets, which is NP-hard in general. Bitmask dynamic programming works for small groups; greedy is the practical default.

How do you keep balances correct when two people add expenses at once?

Lock per group: the membership checks and all balance updates for one expense happen inside synchronized(group). Different groups never contend, split calculation happens before the lock and notifications after it.

How would you support editing or deleting an expense?

Append a reversing expense rather than mutating history, then apply the new one. The ledger stays auditable and balances can always be rebuilt from it if a bug ever corrupts the cached totals.