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
See it run
Bills become shares, shares become moves, and the sum stays zero.
Operations
Add a bill
A tent for 10, shared by Asha, Lee and Noor.
Step 1 of 7
Asha has paid 10
The group gets the payer, the sum and a way to divide.
Step 1: Asha has paid 10
def add(self, payer, cents, split, note): if cents <= 0: raise BadExpense("a bill is more than zero") shares = tuple(split.shares(cents)) people = [s.person for s in shares] if len(set(people)) != len(people) or not known(payer, *people): raise BadExpense("unknown, or named twice") if sum(s.cents for s in shares) != cents: raise BadExpense("the shares do not add up") with self._lock: expense = Expense(next(self._ids), payer, cents, shares, note) self._expenses[expense.id] = expense self._post(expense, 1) return expense- Cost
- O(n log n)
- Guarantee
- Sum stays 0
Everything that can be refused is refused before the lock.
In the real world
The same expense sharing doing real jobs. Pick one and step through it.
Every row adds up to zero.
Step 1 of 5
The tent
| Asha | Lee | Noor | Sam | Sum | |
|---|---|---|---|---|---|
| tent | +6 | -3 | -3 | 0 | 0 |
| boat | |||||
| now | |||||
| pay 1 | |||||
| pay 2 | |||||
| end |
Asha paid 10 and used 4.
Step 1: The tent
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Money as a float
criticalTen times 0.10 is not 1.00, and balances never reach zero.
Wrongshare = total / len(people)Rightparts = allocate(cents, [1] * len(people))Rounding each share
critical33.33 three times is 99.99. The cent has no owner.
Wrongshare = round(100 / 3, 2)Rightparts = [c // n + (i < c % n) for i in range(n)]Two copies of a debt
criticalThey disagree as soon as one step is missed.
Wronglee.owes[asha] += 3asha.owes[lee] -= 3Rightbalances.move(lee, asha, 3)Divide before multiply
major999 // 10000 is 0, and everybody pays nothing.
Wrongcents // whole * wRightcents * w // wholeComputing old shares again
majorAfter a change of the rule, removing a bill leaves cents behind.
Wrongfor s in expense.split.shares(expense.cents): undo(s)Rightfor s in expense.shares: undo(s)A kind of expense for each split
minorThe record needs code to be read, and combinations multiply.
Wrongclass PercentExpense(Expense): ...Rightgroup.add(payer, cents, PercentSplit({...}), note)
Interview tips
Open with
- Whole cents.
- The sum is zero.
- A split makes shares.
Reject aloud
- Debt is worked out.
- User is a string here.
- No expense subclasses.
Prove it
- 10.00 by three.
- Each row adds up.
- All at zero at the end.
Never
- round(total / n).
- Both users' maps.
- Percent as a double.