Design an expense sharing app
medium 80 minDivide bills between friends without losing a cent, keep one balance for each person that always adds up to zero, and settle with at most n - 1 payments.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
An expense sharing app remembers who paid for what in a group, works out what each person is owed, and proposes payments that make everybody even. No real money moves in it.
It has three parts. A split turns a bill into exact shares. Balances book the shares, one number for each person. And simplify turns the balances into a few payments.
The whole design hangs on one sentence: all balances add up to zero. Money is only moved from one person to another, so the sum cannot change.
Why it exists
It is a popular exercise, because everybody has shared a bill, and because the honest solution is short. What is left to judge is precision.
It asks for two skills that meet rarely in one problem: object design, with an interface for what varies, and an algorithm with a bound that can be proved.
Its traps are real in every system with money: fractions of a cent, one fact stored twice, edits without a trace, and requests that arrive two times.
A short history
Middle Ages
Debts in Europe are cut into split tally sticks. Both sides keep a half, and the halves fit only each other.
1494
Luca Pacioli's Summa de arithmetica is published in Venice. Its part on bookkeeping describes double entry: every change has two sides.
1826
The Exchequer in England stops using split tallies. In 1834, after a law of that year, the old sticks were ordered to be destroyed.
1972
Richard Karp lists 21 NP-complete problems, among them Partition. It hides inside the question for the fewest payments.
February 2011
Splitwise is launched, at first as SplitTheRent, for sharing rent.
Words to know
- Expense or bill
- Who paid, how much, and the share of each person.
- Share
- The part of a bill that one person has to bear.
- Split
- The rule that makes shares out of a sum.
- Minor unit
- The smallest unit of a currency, such as a cent.
- Largest remainder
- Round all down, then give the rest to those who lost most.
- Net balance
- All a person is owed minus all they owe.
- Settle
- To pay back, which moves a balance towards zero.
- Simplify
- To replace many debts by few payments with the same result.
- Closed set
- People whose balances add up to zero among themselves.
- Reversal
- A new entry that undoes an older one, and leaves it readable.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Split. A bill becomes exact shares.
Understand it
The problem
Who owes whom, after a week together
Four friends camp for a week. Each of them pays for something, sometimes for all and sometimes for a few. At the end everyone should have paid their fair part, with as little handing around of money as possible. It sounds like adding up. The traps are the cent that cannot be divided, the debt that is written in two places, and the friend who could pay one person and not three.
Twigs say who owes whom. The board says what each person is owed. The board is enough.
Words
What each verb does to the balances
| Verb | Asha | Lee | Noor | Sam | Sum |
|---|---|---|---|---|---|
| Asha pays 10 for Asha, Lee, Noor | +6 | -3 | -3 | 0 | 0 |
| Lee pays 6 for Noor, Sam | 0 | +6 | -3 | -3 | 0 |
| Balance | +6 | +3 | -6 | -3 | 0 |
| Noor pays Asha 6 | -6 | 0 | +6 | 0 | 0 |
| Sam pays Lee 3 | 0 | -3 | 0 | +3 | 0 |
| Balance | 0 | 0 | 0 | 0 | 0 |
First design
What goes wrong with maps in users
The design to avoid: friends who edit each other
1/4A manager with a switch
add(type, ..., values) takes a type and a list that means something else for each type. Every new way to split edits it.
usesextends (is a)
share = round(100.0 / 3, 2) # 33.33total = share * 3print(total, 100.0 - total) # a cent is missing, and nobody owes itassert round(100.0 - total, 2) == 0.01owed = 0.0for _ in range(10): owed += 0.10print(owed == 1.0, owed) # False: ten times 10 cents is not a euroassert owed != 1.0parts = [100_00 // 3 + (i < 100_00 % 3) for i in range(3)]assert parts == [3334, 3333, 3333] and sum(parts) == 100_00Two copies of one debt
Second design
A split makes shares, a group books them
The design to reach: a split makes shares, a group books them
1/7Start from the verbs
Someone pays a bill, a bill was wrong, someone pays someone back, and: who should pay whom? Four methods on one coordinator.
implementsusesdepends onowns (dies together)
allocate is a plain function. It is drawn as a box because it is the most important ten lines of the design.Adding one bill
Division
The cent that is left over
9.99 by 50, 30 and 20 percent
| Person | Exact cents | Rounded down | Lost | Order | Share |
|---|---|---|---|---|---|
| Asha | 499.5 | 499 | 0.5 | 2 | 499 |
| Lee | 299.7 | 299 | 0.7 | 1 | 300 |
| Noor | 199.8 | 199 | 0.8 | 0 | 200 |
| Sum | 999 | 997 | 999 |
How do you keep money?
BreaksFloating point
- How
double amount- Limit
- 0.1 has no exact binary form. Sums drift, and equality tests fail.
- Choose when
- Never for money that must add up.
WorksDecimal
- How
Decimal,BigDecimalwith a scale and a rounding mode- Limit
- Exact for adding. Division still needs a rule for the rest, and every call needs the mode.
- Choose when
- Interest, tax and exchange rates.
StrongWhole cents
- How
- An integer in the smallest unit, and
allocatefor division - Limit
- Formatting happens at the edge, and each currency has its own smallest unit.
- Choose when
- The default here.
Settling
Four debts become two payments
As the bills were made
Simplified
Risks
What can go wrong, and who stops it
A lost cent
Shares do not add up.
allocatehands out the rest, and the group checks the sum again.Two truths
A debt is in two maps. One number for each person, changed in one method.
A double tap
The bill is added twice. The app sends a key, see the page Retries.
Edited history
A changed bill with no trace. Book it backwards and add the new one.
A stranger
A name with a typing mistake. Only members can be booked.
Many payments
Everyone pays everyone. Net first, then match.
Keep
- Whole cents
- Finished shares in the record
- One net number for each person
- A sum that is always zero
- Suggestions worked out on demand
Leave out
- An expense subclass for each split
- Debts in both users
- Percent as a double
- Payment by card in this class
- A global manager
Limits
What this page is, and what it is not
Nobody's bank account is touched here. The group only remembers. Moving real money between accounts is Digital Wallet. Telling friends that a bill was added is notifications. Saying why a class may change its mind about a rule is the Strategy pattern.
Summary
The whole topic in one minute.
Keep money in whole cents. Allocate divides by weights: everybody rounded down, and the rest goes out by largest loss. The parts add up by construction.
A split makes shares, an expense stores them, and balances book them as moves from one person to another. The sum stays zero, and that is the test.
Simplify looks at nets only. At most n - 1 payments clear a group; the true minimum is a hard problem, and small groups can afford it.
- Whole cents, multiplied before they are divided.
- Round down, then give out the rest by largest loss.
- One net number for each person; the sum is zero.
- The record holds finished shares, so undoing is exact.
- At most n - 1 payments clear a group of n.
- Check everything before the first move.