Design an expense-sharing app (like Splitwise)
Design an expense-sharing app like Splitwise: friends and groups record shared expenses, the app tracks who owes whom, and suggests the fewest payments to settle up.
A typical framing: "Four friends go on a trip. Different people pay for the hotel, dinners and taxis, sometimes split equally, sometimes by exact amounts or percentages. Design the classes and API, show how balances are calculated, and how you'd simplify the debts."
TL;DR
Model each expense as who paid and how it's split, and treat money as integer minor units (cents), never floats. Different split types (equal, exact, percentage, shares) are a textbook Strategy pattern: each strategy turns an amount into per-person shares that must add up exactly to the total, so remainders (the leftover cent) are distributed deterministically.
Store expenses and settlements as an append-only ledger; balances are derived from it (and can be cached). The net balance per person is what they paid minus what they owe. Debt simplification settles net balances greedily: repeatedly match the biggest creditor with the biggest debtor, which needs at most n−1 payments. Finding the true minimum number of payments is NP-hard, so the greedy approach is the practical answer.
1. Requirements
Questions worth asking:
- Which split types: equal, exact amounts, percentages, shares?
- Groups only, or also expenses between two friends outside a group?
- One currency or several?
- Can expenses be edited and deleted? Do we need history?
- Should the app suggest simplified payments?
Functional
- Create groups and add members.
- Add an expense: payer(s), amount, split type and participants.
- Show balances: per person in a group, and "you owe / you are owed" overall.
- Record a settlement (a payment between two people).
- Suggest the fewest payments to settle a group.
Non-functional
- Balances are exactly right, to the cent, every time.
- A full audit trail: edits never silently rewrite history.
2. Entities and classes
type Cents = number // always an integer
type Share = { userId: string; amount: Cents }
type Expense = {
id: string
groupId: string
description: string
totalCents: Cents
currency: string
paidBy: Share[] // usually one payer, but can be several
owedBy: Share[] // the result of the split strategy
}3. API
POST /v1/groups { name, memberIds }
POST /v1/groups/{id}/expenses { description, totalCents, currency, paidBy, split: { type, ... } }
PATCH /v1/expenses/{id} -> records a new version, keeps history
GET /v1/groups/{id}/balances -> net balance per member
GET /v1/groups/{id}/settle-up -> suggested payments
POST /v1/groups/{id}/settlements { fromUser, toUser, amountCents }
GET /v1/me/balances -> totals across all groups and friends4. Core logic
Split strategies
interface SplitStrategy {
split(total: Cents, participants: string[], input?: Record<string, number>): Share[]
}
class EqualSplit implements SplitStrategy {
split(total: Cents, participants: string[]): Share[] {
const base = Math.floor(total / participants.length)
let remainder = total - base * participants.length
// 1000 cents among 3 people: 334, 333, 333. The extra cents go to the first people.
return participants.map((userId) => ({ userId, amount: base + (remainder-- > 0 ? 1 : 0) }))
}
}
class PercentSplit implements SplitStrategy {
split(total: Cents, participants: string[], percents: Record<string, number> = {}): Share[] {
const sum = participants.reduce((s, u) => s + (percents[u] ?? 0), 0)
if (Math.abs(sum - 100) > 1e-9) throw new ValidationError('percentages must add up to 100')
const shares = participants.map((u) => ({
userId: u,
amount: Math.floor((total * (percents[u] ?? 0)) / 100),
}))
// Rounding down leaves a few cents; hand them out so the shares add up exactly.
let left = total - shares.reduce((s, x) => s + x.amount, 0)
for (let i = 0; left > 0; i = (i + 1) % shares.length, left--) shares[i]!.amount++
return shares
}
}ExactSplit validates that the given amounts add up to the total, and SharesSplit (2 shares for a couple, 1 for a single person) works like percentages. Every strategy guarantees sum of shares = total.
Balances
function netBalances(expenses: Expense[], settlements: Settlement[]): Map<string, Cents> {
const net = new Map<string, Cents>()
const add = (u: string, v: Cents) => net.set(u, (net.get(u) ?? 0) + v)
for (const e of expenses) {
for (const p of e.paidBy) add(p.userId, p.amount) // paid: others owe you
for (const o of e.owedBy) add(o.userId, -o.amount) // your share: you owe
}
for (const s of settlements) {
add(s.fromUser, s.amountCents)
add(s.toUser, -s.amountCents)
}
return net // positive: is owed money; negative: owes money. Always sums to 0.
}Simplifying debts
function settleUp(net: Map<string, Cents>) {
const creditors = [...net].filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1])
const debtors = [...net]
.filter(([, v]) => v < 0)
.map(([u, v]) => [u, -v] as [string, number])
.sort((a, b) => b[1] - a[1])
const payments: { from: string; to: string; amount: Cents }[] = []
let i = 0
let j = 0
while (i < debtors.length && j < creditors.length) {
const amount = Math.min(debtors[i]![1], creditors[j]![1])
payments.push({ from: debtors[i]![0], to: creditors[j]![0], amount })
debtors[i]![1] -= amount
creditors[j]![1] -= amount
if (debtors[i]![1] === 0) i++
if (creditors[j]![1] === 0) j++
}
return payments // at most (people - 1) payments
}Each step settles at least one person completely, so there are at most n−1 payments. (A heap keeps it "largest first" as balances change; sorting once is a fine simplification.)
5. Edge cases and extensions
- Floats:
0.1 + 0.2 !== 0.3. Use integer cents (or a decimal type in the database:NUMERIC, neverFLOAT). - Editing and deleting: never mutate history in place. Store a new version or a reversing entry, so balances stay explainable ("who changed the dinner from 300 to 450?").
- Multiple currencies: keep balances per currency, and convert only when the user settles, with the exchange rate stored on the settlement.
- Concurrent edits to the same expense: optimistic concurrency with a version number.
- Scale: balances are derived data. For large groups, keep a cached balance table updated in the same transaction as each new ledger entry, and rebuild it from the ledger when needed.
- Simplification across groups: users may prefer to keep debts per group; offer simplification as an opt-in.
Common follow-ups
- "Is greedy optimal?" It guarantees at most n−1 payments but not always the minimum. The true minimum means finding the most subsets of people whose balances sum to zero, which is NP-hard; for small groups you can search it exactly with bitmask DP.
- "Where do the leftover cents go?" Pick a deterministic rule (first participants, or the payer) and apply it consistently, so the same input always gives the same split.
- "How would you add recurring expenses?" A
RecurringExpensetemplate plus a scheduler that creates normal expenses; the ledger stays the same.
What interviewers look for
- Integer money and splits that always add up exactly.
- The Strategy pattern for split types, with validation per type.
- An append-only ledger with balances derived from it.
- A correct net balance calculation and a reasoned debt-simplification algorithm.
- Thinking about edits, history, currencies and concurrency.