LLD: Design Splitwise (Expense Sharing)

System Design · Low-Level Design · Intermediate · 25 min

Design an expense-sharing app: equal, exact and percent splits as strategies, one net balance per person instead of a tangle of IOUs, rounding that never loses a rupee, and a 'settle up' that turns many debts into a few payments.

After a trip, everyone writes how much they paid and how much they used on one sheet. Instead of 'Ben owes Asha, Asha owes Chen, Chen owes Ben...', you just add up each person: who is in the red and who is in the green. Then the red people pay the green people, biggest first.

The idea in everyday words

A class pools money for a picnic. Asha bought the food, Ben the drinks, Chen the cake. Nobody needs a list of who owes whom for each item. The teacher just works out, for each child, 'what you paid minus what you used'. If that number is +350, you get 350 back; if it is -500, you pay 500. Then she pairs the biggest payer with the biggest receiver until everyone is at zero.

Requirements

Must have:

  • Add an expense: who paid, how much, and how it is split.
  • Three split types: equal among a list of people, exact amounts per person, percent per person.
  • Show one person's balance: "gets 350", "owes 500" or "is settled up".
  • Settle up: a short list of payments that brings everyone back to zero.

Questions that change the code:

Question Our answer
Money type? Whole rupees (integers). Never floats for money.
100 split 3 ways? 34 + 33 + 33: the first people in the list pay the extra rupee, so the shares always add up.
Exact amounts that do not add up? Percents that are not 100? Reject the expense with a clear error and change nothing.
Is the payer one of the people sharing? Only if they are listed. "Asha paid 900, split equally among Asha, Ben, Chen" means Asha's own share is 300.
Groups? One group here; a Group class is an easy extension.

The big idea: one net balance per person

A naive design stores every IOU: "Ben owes Asha 300 for dinner", "Asha owes Ben 200 for the taxi". That list grows forever and answering "what does Ben owe overall?" means scanning it.

Better: keep one number per person, the net balance.

  • The payer gets +amount (they paid the whole bill).
  • Every participant gets -share (they used that much), including the payer if they are a participant.

The sum of all balances is always zero: money is never created or lost. That is a great invariant to say out loud and to assert in tests.

Expense asha ben chen
asha pays 900, equal among asha, ben, chen +900 - 300 = +600 -300 -300
ben pays 500, exact: asha 200, chen 300 600 - 200 = +400 -300 + 500 = +200 -300 - 300 = -600
chen pays 100, percent: asha 50, ben 50 400 - 50 = +350 200 - 50 = +150 -600 + 100 = -500

Check: 350 + 150 - 500 = 0. So chen owes 500, and asha and ben are owed 350 and 150.

Rounding without losing money:

amount, people = 100, ["asha", "ben", "chen"]
base, extra = divmod(amount, len(people))
shares = {p: base + (1 if i < extra else 0) for i, p in enumerate(people)}
print(shares, "sum =", sum(shares.values()))

Classes and the split strategies

Ledger
 ├─ net: user -> int               (+ is owed, - owes)
 ├─ add_expense(payer, amount, kind, args) -> "ok" | error
 ├─ balance(user) -> text
 └─ settle() -> [payments]

SplitStrategy (interface)  { shares(amount, args) -> [(user, share)] }
 ├─ EqualSplit     args: users                 extra rupees to the first users
 ├─ ExactSplit     args: user, amount, ...      amounts must add up to the bill
 └─ PercentSplit   args: user, percent, ...     percents must add up to 100

SPLITS = {"equal": EqualSplit, "exact": ExactSplit, "percent": PercentSplit}   (factory table)
  • Strategy again. Each split type answers the same question ("who owes how much of this bill?") in its own way. A new "shares" split (Asha 2 parts, Ben 1 part) is one new class plus one table entry.
  • Validate before you change anything. The strategy raises an error for a bad split, and the ledger only touches balances after the shares are known to be valid. A half-applied expense would break the "sum is zero" invariant.
  • Expense as its own class. In a real app, store each Expense(id, payer, amount, shares, created_at) too, for history, edits and deletes. Deleting an expense is then "apply the same shares with the opposite sign".

Settle up: simplifying debts

Once you have net balances, any set of payments where debtors pay creditors until all balances are zero settles the group. The question is how few payments you can get away with.

Greedy rule (what Splitwise-style apps do in spirit):

  1. Pick the person who owes the most and the person who is owed the most (break ties by name so the answer is repeatable).
  2. The debtor pays the creditor min(debt, credit). At least one of them reaches zero.
  3. Repeat until nobody owes anything.

Each payment zeroes at least one person, so with n people you need at most n - 1 payments. For our trip: chen owes 500; asha is owed 350, ben 150. Payments: chen pays asha 350, chen pays ben 150. Two payments instead of six IOUs.

Is greedy always the fewest payments? No. Finding the true minimum is NP-hard in general (it means finding the most groups of people whose balances sum to zero). Greedy is simple, fast (O(n log n) with two heaps) and never worse than n - 1, which is why interviewers accept it. Say that sentence, and you have shown you know the trade-off.

Go deeper: groups, currencies, history and concurrency

  • Groups. A Group owns members and its own ledger. A user's overall balance is the sum across groups, or settle per group (most apps do per group).
  • Several currencies. Keep one balance per (user, currency). Never convert silently: settle each currency separately, or convert at a stated rate at settle time.
  • Edit and delete. Store expenses as immutable records and derive balances from them (event sourcing). Edit = delete the old record (reverse it) and add a new one. Balances can be cached and rebuilt.
  • Concurrency. Two people add expenses to the same group at once. Each add is "read balances, add deltas, write". Make it atomic: a lock per group, or store only the expense records (an append-only insert is naturally safe) and compute balances from them.
  • Exact minimum payments. For small groups (n up to about 12), a bitmask DP over subsets that sum to zero finds the true minimum: the answer is n minus the largest number of disjoint zero-sum groups.
  • Payments are expenses too. "Ben paid Asha 150" is an exact split where the payer is Ben and the only participant is Asha. One code path, no special case.

Step by step

  1. An equal split:

    expense asha 900 equal asha ben chen: 900 // 3 = 300 each, no extra. asha +900 - 300 = +600, ben -300, chen -300. Output 'ok'.

  2. An exact split:

    expense ben 500 exact asha 200 chen 300: 200 + 300 = 500, valid. ben +500 → +200, asha -200 → +400, chen -300 → -600. Output 'ok'.

  3. A percent split:

    expense chen 100 percent asha 50 ben 50: shares 50 and 50 (add to 100). chen +100 → -500, asha → +350, ben → +150. Sum of all balances: 0.

  4. Balances:

    balance chen → 'chen owes 500'. balance asha → 'asha gets 350'. One number per person answers the question instantly.

  5. Settle: biggest first:

    settle: debtors {chen: 500}, creditors {asha: 350, ben: 150}. chen (owes most) pays asha (owed most) min(500, 350) = 350: 'chen pays asha 350'. asha is now at 0.

  6. Done in two payments:

    chen still owes 150; ben is owed 150: 'chen pays ben 150'. Everyone is at zero. The six original IOUs became two payments.

Code example

# Pairwise IOUs versus net balances, for the same three expenses.
ious = [("ben", "asha", 300), ("chen", "asha", 300),     # asha paid 900, equal
        ("asha", "ben", 200), ("chen", "ben", 300),      # ben paid 500, exact
        ("asha", "chen", 50), ("ben", "chen", 50)]       # chen paid 100, percent

net = {}
for debtor, creditor, amount in ious:
    net[debtor] = net.get(debtor, 0) - amount
    net[creditor] = net.get(creditor, 0) + amount

print("IOUs to pay one by one:", len(ious))
print("net balances:", net, "sum =", sum(net.values()))

owe = sorted((-v, u) for u, v in net.items() if v < 0)
get = sorted((-v, u) for u, v in net.items() if v > 0)
print("biggest debtor:", owe[0][1], "biggest creditor:", get[0][1])

Complexity

  • Time: O(k) per expense with k participants; settle O(n²) as written (O(n log n) with two heaps)
  • Space: O(n): one balance per person

Interview tips

  • Lead with the data model: one net balance per user, payer +amount, participants -share. Then state the sum-is-zero invariant.

  • Use integers for money and say how the leftover rupee is assigned.

  • Model split types as Strategies and show that a new 'shares' split is one class.

  • For settle, describe the greedy and its bound (at most n - 1 payments), then mention that the exact minimum is NP-hard and solvable with bitmask DP for small groups.

  • If asked about edits, history or concurrency: store immutable expense records, derive balances, and lock per group (or use append-only inserts).

Challenge: Splitwise: Split, Balance, Settle

Write run_splitwise(ops) for one group. Amounts are whole rupees. Return a list of output lines.

Command Output
expense <payer> <amount> equal <u1> <u2> ... ok
expense <payer> <amount> exact <u1> <a1> <u2> <a2> ... ok, or error: exact split adds up to <sum>, not <amount>
expense <payer> <amount> percent <u1> <p1> <u2> <p2> ... ok, or error: percents add up to <sum>, not 100
any other split type error: unknown split <type>
balance <user> <user> gets <n>, <user> owes <n>, or <user> is settled up
settle one line per payment: <debtor> pays <creditor> <n>, or the single line all settled up

Rules:

  • The payer's balance goes up by the whole amount; every listed participant's balance goes down by their share (the payer too, if listed). A rejected expense changes nothing.
  • equal: amount // n each; the leftover rupees go one each to the first people in the list.
  • percent: each share is amount * p // 100; the rupees lost to rounding go one each to the first people in the list.
  • settle does not change balances. Repeat: the person who owes the most pays the person who is owed the most min(debt, credit). Ties go to the name that sorts first.

Example:

run_splitwise(["expense asha 900 equal asha ben chen",
               "expense ben 500 exact asha 200 chen 300",
               "expense chen 100 percent asha 50 ben 50", "balance chen", "settle"])
  -> ["ok", "ok", "ok", "chen owes 500", "chen pays asha 350", "chen pays ben 150"]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Low-Level Design

Previous: LLD: Design a Rate Limiter (Classes and Strategies) · Next: LLD: Design Movie Ticket Booking (BookMyShow)