AlgoViz

Design an expense sharing app

medium 80 min

Divide 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

0:00 / 4:24

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

  1. Middle Ages

    Debts in Europe are cut into split tally sticks. Both sides keep a half, and the halves fit only each other.

  2. 1494

    Luca Pacioli's Summa de arithmetica is published in Venice. Its part on bookkeeping describes double entry: every change has two sides.

  3. 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.

  4. 1972

    Richard Karp lists 21 NP-complete problems, among them Partition. It hides inside the question for the fewest payments.

  5. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

Camping friends and IOU twigs
Asha 0Lee 0Noor 0Sam 0sum 0AshaLeeNoorSam

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

VerbAshaLeeNoorSamSum
Asha pays 10 for Asha, Lee, Noor+6-3-300
Lee pays 6 for Noor, Sam0+6-3-30
Balance+6+3-6-30
Noor pays Asha 6-60+600
Sam pays Lee 30-30+30
Balance00000
Every row adds up to zero. If one does not, the mistake is in that row.

First design

What goes wrong with maps in users

The design to avoid: friends who edit each other

ExpenseManager- instance: ExpenseManager+ add(type, amount, users, values)+ printBalances()

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)

The names are all sensible. What is missing is one place where a debt lives, and one rule that can be checked.
Python
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_00
Two different bugs. The first is division, the second is binary fractions. Whole cents cure the second; only a rule for the rest cures the first.
Edit and run it in your browser

Two copies of one debt

In the middle the two maps disagree, and a reader sees it. If the last step fails, they disagree for ever.

Second design

A split makes shares, a group books them

The design to reach: a split makes shares, a group books them

Group- expenses: Map<id, Expense>- payments: List<Transfer>- lock: Lock+ add(payer, cents, split, note)+ remove(id)+ settle(payer, receiver, cents)+ suggest(): List<Transfer>

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

Everything that can be refused is refused before the first move.

Division

The cent that is left over

9.99 by 50, 30 and 20 percent

PersonExact centsRounded downLostOrderShare
Asha499.54990.52499
Lee299.72990.71300
Noor199.81990.80200
Sum999997999
Two cents are left. Noor and Lee lost most by rounding, so they get one each. Rounding each share to the nearest cent would give 500, 300 and 200: one cent too many.
Known as the largest remainder method. Parliaments use it to turn votes into seats, which is the same problem.

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, BigDecimal with 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 allocate for 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

Everyone pays or gets the same total as before. Only the partners changed.

Risks

What can go wrong, and who stops it

  • A lost cent

    Shares do not add up. allocate hands 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.

Sources