Splitwise looks like a CRUD app with a sum at the end, and that is why candidates underprepare for it. Three things make it a real design question. Money does not divide: ₹100 split three ways is not ₹33.33 each, because that adds up to ₹99.99 and somebody has to own the missing paisa. Balances have to stay consistent with a history that people edit and delete. And “settle up” hides an optimisation problem whose exact answer is NP-hard, so the interviewer can keep asking “can you do better?” for as long as they like.
The answer below takes about 300 lines of Python or 340 of Java and runs end to end.
Scope
In:
- Users belong to groups. An expense has one payer, an amount, and a split among some or all of the group’s members.
- Four split types: equal (optionally among a subset), exact amounts, percentages, and shares (2:1:1 for “Aman and Divya ate double”).
- Each member’s net balance in the group: positive means the group owes them, negative means they owe.
- Who owes whom, both raw (pair by pair) and simplified to fewer transfers.
- Record a settle-up payment. Delete an expense.
- Several members adding expenses to the same group at the same time.
Out, and I would say so early:
- Multiple currencies. Everything is in rupees, stored as paise. The extension below explains what changes.
- Several payers on one expense (“Aman paid ₹2,000 and Bela paid ₹750 of the dinner”). Real Splitwise supports it; in an interview it doubles the validation code without adding a new idea. I mention it as a follow-up.
- Friends outside groups, recurring expenses, receipts and photos, comments, notifications, login.
- Actually moving money. “Settle up” records that a payment happened; UPI does the paying.
Where the truth lives
The decision that shapes everything else: what is stored, and what is computed from it?
I store the list of expenses as the source of truth, and keep a net balance per member as a cache that every write updates. “Who owes whom” is never stored; it is computed when someone opens the screen.
The alternative most people draw first is a pairwise ledger, owes[a][b], updated on every expense. It works until someone edits an expense from three weeks ago. Then you have to know exactly which pair entries that expense touched, undo them, and apply the new ones, and a single bug leaves the ledger permanently out of step with the expenses it was built from. With an expense list, the worst case of a bug in the cache is “recompute the balances from the list”, which is a loop. Deleting an expense in the code is exactly that: remove it and apply it with the opposite sign.
The cache has one invariant that makes testing easy: net balances in a group always sum to zero, to the paisa. Every payment in is somebody’s debt out. The demo asserts it after every step.
Entities:
Group: members, expenses by id, net balance per member, a lock, and the next expense id.Expense: immutable. Id, description, payer, amount in paise, and the resolved map of who owes how much. A settle-up payment is also anExpense, flaggedis_payment.Split: an interface with one method,owed(total, members), returning paise per person.EqualSplit,ExactSplit,PercentSplit,ShareSplitimplement it.- Two free functions for settling up:
greedy_planandminimum_plan, both taking the net balances and returning a list of transfers.
There is no User class. A member is a name here; in a real system it is a user id, and the User entity (phone, email, UPI handle) belongs to a different service. There is no Balance class either. A balance is a number in a map.
classDiagram
class Group {
+name: str
+members: list~str~
+expenses: dict~int, Expense~
+net: dict~str, int~
-next_id: int
-lock: Lock
+add_expense(desc, paid_by, amount, split) Expense
+settle(payer, payee, amount) Expense
+delete(expense_id) Expense
+pairwise() list
}
class Expense {
<<immutable>>
+id: int
+description: str
+paid_by: str
+amount: int
+owed: dict~str, int~
+is_payment: bool
}
class Split {
<<interface>>
+owed(total, members) dict~str, int~
}
class EqualSplit {
+among: list~str~
}
class ExactSplit {
+amounts: dict~str, int~
}
class PercentSplit {
+percents: dict~str, int~
}
class ShareSplit {
+shares: dict~str, int~
}
class SettleUp {
<<functions>>
+greedy_plan(net) list
+minimum_plan(net) list
}
Group "1" *-- "*" Expense
Group ..> Split : resolves with
Split <|.. EqualSplit
Split <|.. ExactSplit
Split <|.. PercentSplit
Split <|.. ShareSplit
SettleUp ..> Group : reads netPaise, and who gets the odd one
Store money as an integer number of paise. With floating point, 0.1 + 0.2 is 0.30000000000000004, and a group’s balances drift away from zero one expense at a time. With integers, the only hard question is what to do with the remainder.
allocate(total, weights) handles every proportional split. Each person gets the floor of their exact share; whatever paise are left over (always fewer than the number of people) go one each to the people whose exact share had the largest fractional part. Ties go to whoever is listed first, so the result is deterministic. This is the largest remainder method, and it guarantees two things: the parts add up to exactly the total, and nobody is more than one paisa away from their exact share.
Two examples from the demo:
- The ₹100 airport cab, split equally among Bela, Chirag and Divya: 10,000 paise / 3 is 3,333 each with 1 left over. All three remainders are equal, so Bela, listed first, pays ₹33.34 and the other two ₹33.33.
- ₹999.99 of groceries split by shares 2:1:1:2. Aman’s and Divya’s exact share is 33,333 paise with nothing left over. Bela’s and Chirag’s is 16,666.5 each; both get 16,666, and the one leftover paisa goes to Bela. Result: ₹333.33, ₹166.67, ₹166.66, ₹333.33.
“Ties to the first listed” is a choice, and the interviewer may not like it: the same person always eats the extra paisa. Alternatives are giving it to the payer (they are owed slightly less) or rotating it. Any of them is fine as long as it is deterministic and documented; what is not fine is round() on each share, which gives ₹33.33 three times and loses a paisa per expense.
Exact splits do not go through allocate. They are validated instead: the amounts must add up to the total, to the paisa, or the expense is refused.
Patterns, and what I left out
Strategy for split types. Four ways of turning a total into shares, one interface, and the group does not know which it has. The more important point is where validation sits: each strategy checks its own input (percentages sum to 100, exact amounts sum to the total, shares are positive), and the group checks only what is common to all of them (payer and every person in the split are members, no negative shares). Adding “split by nights stayed” is a new class; nothing in Group changes.
The strategy returns a fully resolved map of paise. That is deliberate. The stored Expense holds the resolved amounts, not “40% / 30% / 30%”. If the rounding rule ever changes, old expenses keep the amounts people already saw and agreed to.
Immutable expenses. Not a GoF pattern, but the one design choice that matters most here. An edit is “delete the old one, add a new one”, and both go through the same _apply with a sign. There is no code path that mutates an expense in place, so the balances can always be rebuilt from the list.
Considered and dropped:
- Factory for splits (
SplitFactory.create("PERCENT", ...)). This is in almost every Splitwise answer online. It turns a typed constructor call into a string switch, and you still have to pass type-specific arguments, so the caller already knows the type. It makes sense at the API boundary, where a JSON request carries"type": "percent"; that parsing code is where I would put it, not inside the model. - Observer for notifications. “Bela added an expense” is a real feature, but it is a side effect of a committed write, best done by publishing an event after the transaction commits. Inside the model, an observer list adds a way for a slow email sender to hold the group’s lock.
- Singleton
ExpenseManager. Many groups exist at once and each has its own lock. A singleton manager is where people end up with one global lock around everything. - Command for undo. Delete-by-reversal already gives undo, and the expense list is the history.
Settling up
After the trip, the app should tell people who pays whom. There are three levels of answer.
Raw, pair by pair. Every share becomes a debt to that expense’s payer, netted between the same two people. In the demo’s Goa group this gives 6 debts among 4 people. Correct, and annoying: Divya pays three different people.
Greedy simplification. Ignore who paid for what and look only at net balances. Repeatedly take the person who owes the most and the person owed the most, and transfer the smaller of the two amounts. Each step zeroes at least one person, so n people with non-zero balances need at most n − 1 transfers. In the Goa group Aman is the only creditor, so it is 3 transfers, all to Aman. This is the answer most interviews expect, and it is O(n log n) with a heap.
Simplification changes who pays whom. In the raw view Divya owed Chirag ₹133.34; in the simplified view she pays Aman directly and Chirag pays nobody that money. The totals per person are the same, but some users find it confusing to pay someone they did not borrow from. That is why Splitwise has a per-group “simplify debts” setting, and why pairwise() is kept alongside the plan.
The true minimum. Greedy is not optimal. Take six friends with balances −₹900, −₹800, −₹500, +₹700, +₹700, +₹800. Greedy starts with the biggest debtor (−₹900) and the biggest creditor (+₹800), which breaks up the perfect pair of −₹800 and +₹800 and costs 5 transfers. The minimum is 4: Bela pays Farhan ₹800, and the other four settle among themselves in 3.
The general rule: if the people with non-zero balances can be split into k groups that each sum to zero, you need exactly n − k transfers, and the minimum is n minus the largest such k. Finding that k is NP-hard (it is a close relative of the partition problems), so nobody solves it exactly for a thousand people. For a group of friends it is easy: minimum_plan does a bitmask DP over subsets, O(2ⁿ · n), which is instant at 6 people and still fine around 20.
How often does it matter? I generated 10,000 random six-person groups with balances in whole multiples of ₹100 (between −₹2,000 and +₹2,000 for five people, the sixth balancing them). Greedy used more transfers than the minimum in 916 of them, about 9%, and in every one of those it was exactly one extra transfer. That is a fair summary to give an interviewer: greedy is the right default, a cheap improvement is to match exact opposite pairs first, and the exponential search is only worth it for small groups.
The code
Both versions were run on the box this lesson was written on (Python 3.13.5, OpenJDK 21.0.13) and print byte-for-byte identical output. Demo 7 uses threads, but its printed totals do not depend on scheduling: addition is commutative and each thread’s expenses are the same whatever order they land in. Files and expected-output.txt are in course-code/low-level-design/16/ in the course repository.
Before reading:
add_expenseresolves and validates the split before taking the lock. Only the id assignment, the insert and the balance update are inside it. A slow or failing validation never blocks other writers.settlerecords a payment as an expense paid by the debtor and owed entirely by the creditor. That is all a payment is, arithmetically, and it means payments and expenses share one code path.minimum_planfirst finds an order of people in which every zero-sum group appears as a run, then runs the greedy plan inside each group. Within a zero-sum group of size m, greedy uses at most m − 1 transfers, which is optimal for a group that cannot be split further.
Python
"""Splitwise low-level design: split strategies, paise-exact rounding, group balances,
and two ways to settle up (greedy and the true minimum number of transfers).
Run: python3 splitwise.py
"""
from __future__ import annotations
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
class SplitError(Exception):
pass
def rs(paise: int) -> str:
sign = "-" if paise < 0 else ""
p = abs(paise)
return f"{sign}Rs {p // 100}.{p % 100:02d}"
def allocate(total: int, weights: list[int]) -> list[int]:
"""Split `total` paise in proportion to `weights`, summing to exactly `total`.
Everyone gets the floor of their share; leftover paise go to the largest remainders,
ties to whoever is listed first."""
wsum = sum(weights)
base = [total * w // wsum for w in weights]
rem = [total * w % wsum for w in weights]
order = sorted(range(len(weights)), key=lambda i: (-rem[i], i))
for i in order[: total - sum(base)]:
base[i] += 1
return base
# ---------------- split strategies ----------------
class Split(ABC):
@abstractmethod
def owed(self, total: int, members: list[str]) -> dict[str, int]:
"""Who owes how many paise of `total`. Must sum to `total`."""
class EqualSplit(Split):
def __init__(self, among: list[str] | None = None) -> None:
self.among = among # None means the whole group
def owed(self, total, members):
people = self.among or members
return dict(zip(people, allocate(total, [1] * len(people))))
class ExactSplit(Split):
def __init__(self, amounts: dict[str, int]) -> None:
self.amounts = amounts
def owed(self, total, members):
given = sum(self.amounts.values())
if given != total:
raise SplitError(f"exact amounts add up to {rs(given)}, expense is {rs(total)}")
return dict(self.amounts)
class PercentSplit(Split):
def __init__(self, percents: dict[str, int]) -> None:
self.percents = percents
def owed(self, total, members):
if sum(self.percents.values()) != 100:
raise SplitError(f"percentages add up to {sum(self.percents.values())}, not 100")
return dict(zip(self.percents, allocate(total, list(self.percents.values()))))
class ShareSplit(Split):
def __init__(self, shares: dict[str, int]) -> None:
self.shares = shares
def owed(self, total, members):
if any(s <= 0 for s in self.shares.values()):
raise SplitError("shares must be positive")
return dict(zip(self.shares, allocate(total, list(self.shares.values()))))
# ---------------- expenses and the group ----------------
@dataclass(frozen=True)
class Expense:
id: int
description: str
paid_by: str
amount: int
owed: dict[str, int]
is_payment: bool = False
class Group:
def __init__(self, name: str, members: list[str]) -> None:
self.name = name
self.members = list(members)
self.expenses: dict[int, Expense] = {}
self.net = {m: 0 for m in members} # + means the group owes you, - means you owe
self._next_id = 1
self._lock = threading.Lock()
def add_expense(self, description: str, paid_by: str, amount: int, split: Split) -> Expense:
self._check_member(paid_by)
if amount <= 0:
raise SplitError("amount must be positive")
owed = split.owed(amount, self.members) # validate before taking the lock
for person, share in owed.items():
self._check_member(person)
if share < 0:
raise SplitError(f"negative share for {person}")
return self._record(description, paid_by, amount, owed, False)
def settle(self, payer: str, payee: str, amount: int) -> Expense:
"""A payment is an expense paid by the debtor and owed entirely by the creditor."""
self._check_member(payer)
self._check_member(payee)
return self._record(f"{payer} paid {payee}", payer, amount, {payee: amount}, True)
def delete(self, expense_id: int) -> Expense:
with self._lock:
exp = self.expenses.pop(expense_id)
self._apply(exp, -1)
return exp
def _record(self, description, paid_by, amount, owed, is_payment) -> Expense:
with self._lock:
exp = Expense(self._next_id, description, paid_by, amount, owed, is_payment)
self._next_id += 1
self.expenses[exp.id] = exp
self._apply(exp, +1)
return exp
def _apply(self, exp: Expense, sign: int) -> None:
self.net[exp.paid_by] += sign * exp.amount
for person, share in exp.owed.items():
self.net[person] -= sign * share
def _check_member(self, person: str) -> None:
if person not in self.net:
raise SplitError(f"{person} is not in {self.name}")
def pairwise(self) -> list[tuple[str, str, int]]:
"""Who owes whom with no simplification: each share is a debt to that expense's payer,
netted only between the same two people."""
debt: dict[tuple[str, str], int] = {}
for exp in self.expenses.values():
for person, share in exp.owed.items():
if person != exp.paid_by:
debt[(person, exp.paid_by)] = debt.get((person, exp.paid_by), 0) + share
out = []
for i, a in enumerate(self.members):
for b in self.members[i + 1:]:
d = debt.get((a, b), 0) - debt.get((b, a), 0)
if d > 0:
out.append((a, b, d))
elif d < 0:
out.append((b, a, -d))
return out
# ---------------- settling up ----------------
def greedy_plan(net: dict[str, int]) -> list[tuple[str, str, int]]:
"""Largest debtor pays largest creditor, repeat. At most n-1 transfers, not always the fewest."""
bal = dict(net)
order = {p: i for i, p in enumerate(net)}
plan = []
while True:
creditors = [p for p in bal if bal[p] > 0]
if not creditors:
return plan
c = max(creditors, key=lambda p: (bal[p], -order[p]))
d = min((p for p in bal if bal[p] < 0), key=lambda p: (bal[p], order[p]))
x = min(bal[c], -bal[d])
plan.append((d, c, x))
bal[c] -= x
bal[d] += x
def minimum_plan(net: dict[str, int]) -> list[tuple[str, str, int]]:
"""Fewest transfers. n people with non-zero balances need n - k transfers, where k is the
largest number of groups they can be split into that each sum to zero. Finding k is NP-hard;
this bitmask DP is exact and fine up to about 20 people."""
people = [p for p in net if net[p] != 0]
n = len(people)
full = (1 << n) - 1
total = [0] * (full + 1)
best = [0] * (full + 1)
for m in range(1, full + 1):
low = (m & -m).bit_length() - 1
total[m] = total[m & (m - 1)] + net[people[low]]
best[m] = max(best[m ^ (1 << i)] for i in range(n) if m >> i & 1) + (total[m] == 0)
# Walk back from the full set to recover an order in which zero-sum groups appear as prefixes.
order, m = [], full
while m:
i = next(i for i in range(n) if m >> i & 1
and best[m ^ (1 << i)] + (total[m] == 0) == best[m])
order.append(people[i])
m ^= 1 << i
order.reverse()
plan, chunk, running = [], {}, 0
for p in order:
chunk[p] = net[p]
running += net[p]
if running == 0:
plan += greedy_plan(chunk)
chunk = {}
return plan
# ---------------- demo ----------------
def show_plan(plan) -> None:
for frm, to, amt in plan:
print(f" {frm:<7} pays {to:<7} {rs(amt):>12}")
def show_net(g: Group) -> None:
for m in g.members:
print(f" {m:<7} {rs(g.net[m]):>12}")
assert sum(g.net.values()) == 0
def main() -> None:
goa = Group("Goa trip", ["Aman", "Bela", "Chirag", "Divya"])
print("1) Five expenses, four split types")
for exp in (
goa.add_expense("hotel", "Aman", 12_000_00, EqualSplit()),
goa.add_expense("dinner", "Bela", 2_750_00,
ExactSplit({"Aman": 800_00, "Bela": 650_00, "Chirag": 700_00, "Divya": 600_00})),
goa.add_expense("scooters", "Chirag", 1_000_00, PercentSplit({"Aman": 40, "Chirag": 30, "Divya": 30})),
goa.add_expense("groceries", "Divya", 999_99, ShareSplit({"Aman": 2, "Bela": 1, "Chirag": 1, "Divya": 2})),
goa.add_expense("airport cab", "Aman", 100_00, EqualSplit(["Bela", "Chirag", "Divya"])),
):
shares = ", ".join(f"{p} {rs(s)}" for p, s in exp.owed.items())
print(f" #{exp.id} {exp.description:<11} {rs(exp.amount):>11} paid by {exp.paid_by:<6} -> {shares}")
print("\n2) Bad input is refused before anything is recorded")
bad = [
("dinner", "Bela", 2_750_00, ExactSplit({"Aman": 800_00, "Bela": 650_00, "Chirag": 700_00, "Divya": 550_00})),
("scooters", "Chirag", 1_000_00, PercentSplit({"Aman": 40, "Chirag": 30, "Divya": 20})),
("parasailing", "Esha", 3_000_00, EqualSplit()),
("snacks", "Aman", 300_00, EqualSplit(["Aman", "Farhan"])),
]
for args in bad:
try:
goa.add_expense(*args)
except SplitError as e:
print(f" {args[0]:<11} refused: {e}")
print(f" expenses recorded: {len(goa.expenses)}")
print("\n3) Net balance per person (+ is owed to them)")
show_net(goa)
print("\n4) Who owes whom, unsimplified:", len(goa.pairwise()), "debts")
show_plan(goa.pairwise())
print(" Simplified:", len(greedy_plan(goa.net)), "transfers")
show_plan(greedy_plan(goa.net))
print("\n5) Chirag settles, then the cab is deleted")
goa.settle("Chirag", "Aman", 2_600_00)
removed = goa.delete(5)
print(f" recorded payment Chirag -> Aman Rs 2600.00, deleted #{removed.id} {removed.description}")
show_net(goa)
show_plan(greedy_plan(goa.net))
print("\n6) Greedy is not always the fewest transfers")
trip = {"Aman": -900_00, "Bela": -800_00, "Chirag": -500_00,
"Divya": 700_00, "Esha": 700_00, "Farhan": 800_00}
g, best = greedy_plan(trip), minimum_plan(trip)
print(f" greedy: {len(g)} transfers")
show_plan(g)
print(f" minimum: {len(best)} transfers")
show_plan(best)
print("\n7) Eight threads add 100 expenses each to one group")
flat = Group("Flat 4B", ["Aman", "Bela", "Chirag", "Divya"])
def spam(t: int) -> None:
payer = flat.members[t % 4]
for _ in range(100):
flat.add_expense("chai", payer, 10_00 + t, EqualSplit())
threads = [threading.Thread(target=spam, args=(t,)) for t in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
ids = sorted(flat.expenses)
print(f" {len(flat.expenses)} expenses, ids {ids[0]}..{ids[-1]}, balances sum to {rs(sum(flat.net.values()))}")
show_net(flat)
if __name__ == "__main__":
main()
Java
// Splitwise low-level design: split strategies, paise-exact rounding, group balances,
// and two ways to settle up (greedy and the true minimum number of transfers).
// Run: javac Splitwise.java && java Splitwise
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public class Splitwise {
static class SplitError extends RuntimeException {
SplitError(String msg) { super(msg); }
}
static String rs(long paise) {
String sign = paise < 0 ? "-" : "";
long p = Math.abs(paise);
return String.format("%sRs %d.%02d", sign, p / 100, p % 100);
}
/** Split total paise in proportion to weights, summing to exactly total. Everyone gets the floor
* of their share; leftover paise go to the largest remainders, ties to whoever is listed first. */
static long[] allocate(long total, int[] weights) {
long wsum = 0;
for (int w : weights) wsum += w;
long[] base = new long[weights.length];
long[] rem = new long[weights.length];
long given = 0;
for (int i = 0; i < weights.length; i++) {
base[i] = total * weights[i] / wsum;
rem[i] = total * weights[i] % wsum;
given += base[i];
}
Integer[] order = new Integer[weights.length];
for (int i = 0; i < order.length; i++) order[i] = i;
Arrays.sort(order, (a, b) -> rem[a] != rem[b] ? Long.compare(rem[b], rem[a]) : Integer.compare(a, b));
for (int k = 0; k < total - given; k++) base[order[k]]++;
return base;
}
static LinkedHashMap<String, Long> byWeight(long total, Map<String, Integer> weights) {
int[] w = weights.values().stream().mapToInt(Integer::intValue).toArray();
long[] parts = allocate(total, w);
LinkedHashMap<String, Long> out = new LinkedHashMap<>();
int i = 0;
for (String p : weights.keySet()) out.put(p, parts[i++]);
return out;
}
// ---------------- split strategies ----------------
interface Split {
/** Who owes how many paise of total. Must sum to total. */
Map<String, Long> owed(long total, List<String> members);
}
static class EqualSplit implements Split {
final List<String> among; // null means the whole group
EqualSplit() { this(null); }
EqualSplit(List<String> among) { this.among = among; }
public Map<String, Long> owed(long total, List<String> members) {
Map<String, Integer> w = new LinkedHashMap<>();
for (String p : among != null ? among : members) w.put(p, 1);
return byWeight(total, w);
}
}
static class ExactSplit implements Split {
final Map<String, Long> amounts;
ExactSplit(Map<String, Long> amounts) { this.amounts = amounts; }
public Map<String, Long> owed(long total, List<String> members) {
long given = amounts.values().stream().mapToLong(Long::longValue).sum();
if (given != total)
throw new SplitError("exact amounts add up to " + rs(given) + ", expense is " + rs(total));
return new LinkedHashMap<>(amounts);
}
}
static class PercentSplit implements Split {
final Map<String, Integer> percents;
PercentSplit(Map<String, Integer> percents) { this.percents = percents; }
public Map<String, Long> owed(long total, List<String> members) {
int sum = percents.values().stream().mapToInt(Integer::intValue).sum();
if (sum != 100) throw new SplitError("percentages add up to " + sum + ", not 100");
return byWeight(total, percents);
}
}
static class ShareSplit implements Split {
final Map<String, Integer> shares;
ShareSplit(Map<String, Integer> shares) { this.shares = shares; }
public Map<String, Long> owed(long total, List<String> members) {
for (int s : shares.values()) if (s <= 0) throw new SplitError("shares must be positive");
return byWeight(total, shares);
}
}
// ---------------- expenses and the group ----------------
record Expense(int id, String description, String paidBy, long amount, Map<String, Long> owed, boolean isPayment) {}
record Transfer(String from, String to, long amount) {}
static class Group {
final String name;
final List<String> members;
final LinkedHashMap<Integer, Expense> expenses = new LinkedHashMap<>();
final LinkedHashMap<String, Long> net = new LinkedHashMap<>(); // + means the group owes you
private int nextId = 1;
private final ReentrantLock lock = new ReentrantLock();
Group(String name, List<String> members) {
this.name = name;
this.members = List.copyOf(members);
for (String m : members) net.put(m, 0L);
}
Expense addExpense(String description, String paidBy, long amount, Split split) {
checkMember(paidBy);
if (amount <= 0) throw new SplitError("amount must be positive");
Map<String, Long> owed = split.owed(amount, members); // validate before taking the lock
for (var e : owed.entrySet()) {
checkMember(e.getKey());
if (e.getValue() < 0) throw new SplitError("negative share for " + e.getKey());
}
return record(description, paidBy, amount, owed, false);
}
/** A payment is an expense paid by the debtor and owed entirely by the creditor. */
Expense settle(String payer, String payee, long amount) {
checkMember(payer);
checkMember(payee);
Map<String, Long> owed = new LinkedHashMap<>();
owed.put(payee, amount);
return record(payer + " paid " + payee, payer, amount, owed, true);
}
Expense delete(int id) {
lock.lock();
try {
Expense e = expenses.remove(id);
apply(e, -1);
return e;
} finally { lock.unlock(); }
}
private Expense record(String description, String paidBy, long amount, Map<String, Long> owed, boolean isPayment) {
lock.lock();
try {
Expense e = new Expense(nextId++, description, paidBy, amount, Collections.unmodifiableMap(owed), isPayment);
expenses.put(e.id(), e);
apply(e, 1);
return e;
} finally { lock.unlock(); }
}
private void apply(Expense e, int sign) {
net.merge(e.paidBy(), sign * e.amount(), Long::sum);
e.owed().forEach((p, share) -> net.merge(p, -sign * share, Long::sum));
}
private void checkMember(String p) {
if (!net.containsKey(p)) throw new SplitError(p + " is not in " + name);
}
/** Who owes whom with no simplification: each share is a debt to that expense's payer,
* netted only between the same two people. */
List<Transfer> pairwise() {
Map<String, Long> debt = new HashMap<>();
for (Expense e : expenses.values())
e.owed().forEach((p, share) -> {
if (!p.equals(e.paidBy())) debt.merge(p + ">" + e.paidBy(), share, Long::sum);
});
List<Transfer> out = new ArrayList<>();
for (int i = 0; i < members.size(); i++)
for (int j = i + 1; j < members.size(); j++) {
String a = members.get(i), b = members.get(j);
long d = debt.getOrDefault(a + ">" + b, 0L) - debt.getOrDefault(b + ">" + a, 0L);
if (d > 0) out.add(new Transfer(a, b, d));
else if (d < 0) out.add(new Transfer(b, a, -d));
}
return out;
}
}
// ---------------- settling up ----------------
/** Largest debtor pays largest creditor, repeat. At most n-1 transfers, not always the fewest. */
static List<Transfer> greedyPlan(Map<String, Long> net) {
LinkedHashMap<String, Long> bal = new LinkedHashMap<>(net);
List<Transfer> plan = new ArrayList<>();
while (true) {
String c = null, d = null;
for (var e : bal.entrySet()) {
long v = e.getValue();
if (v > 0 && (c == null || v > bal.get(c))) c = e.getKey();
if (v < 0 && (d == null || v < bal.get(d))) d = e.getKey();
}
if (c == null) return plan;
long x = Math.min(bal.get(c), -bal.get(d));
plan.add(new Transfer(d, c, x));
bal.put(c, bal.get(c) - x);
bal.put(d, bal.get(d) + x);
}
}
/** Fewest transfers. n people with non-zero balances need n - k transfers, where k is the largest
* number of groups they can be split into that each sum to zero. Finding k is NP-hard; this
* bitmask DP is exact and fine up to about 20 people. */
static List<Transfer> minimumPlan(Map<String, Long> net) {
List<String> people = new ArrayList<>();
net.forEach((p, v) -> { if (v != 0) people.add(p); });
int n = people.size(), full = (1 << n) - 1;
long[] total = new long[full + 1];
int[] best = new int[full + 1];
for (int m = 1; m <= full; m++) {
int low = Integer.numberOfTrailingZeros(m);
total[m] = total[m & (m - 1)] + net.get(people.get(low));
int b = 0;
for (int i = 0; i < n; i++) if ((m >> i & 1) == 1) b = Math.max(b, best[m ^ (1 << i)]);
best[m] = b + (total[m] == 0 ? 1 : 0);
}
// Walk back from the full set to recover an order in which zero-sum groups appear as prefixes.
List<String> order = new ArrayList<>();
for (int m = full; m != 0; ) {
for (int i = 0; i < n; i++) {
if ((m >> i & 1) == 1 && best[m ^ (1 << i)] + (total[m] == 0 ? 1 : 0) == best[m]) {
order.add(people.get(i));
m ^= 1 << i;
break;
}
}
}
Collections.reverse(order);
List<Transfer> plan = new ArrayList<>();
LinkedHashMap<String, Long> chunk = new LinkedHashMap<>();
long running = 0;
for (String p : order) {
chunk.put(p, net.get(p));
running += net.get(p);
if (running == 0) {
plan.addAll(greedyPlan(chunk));
chunk = new LinkedHashMap<>();
}
}
return plan;
}
// ---------------- demo ----------------
static void showPlan(List<Transfer> plan) {
for (Transfer t : plan) System.out.println(String.format(" %-7s pays %-7s %12s", t.from(), t.to(), rs(t.amount())));
}
static void showNet(Group g) {
long sum = 0;
for (String m : g.members) {
System.out.println(String.format(" %-7s %12s", m, rs(g.net.get(m))));
sum += g.net.get(m);
}
if (sum != 0) throw new AssertionError("balances do not sum to zero");
}
static <V> LinkedHashMap<String, V> map(Object... kv) {
LinkedHashMap<String, V> m = new LinkedHashMap<>();
for (int i = 0; i < kv.length; i += 2) {
@SuppressWarnings("unchecked") V v = (V) kv[i + 1];
m.put((String) kv[i], v);
}
return m;
}
public static void main(String[] args) throws Exception {
Group goa = new Group("Goa trip", List.of("Aman", "Bela", "Chirag", "Divya"));
System.out.println("1) Five expenses, four split types");
List<Expense> added = List.of(
goa.addExpense("hotel", "Aman", 12_000_00, new EqualSplit()),
goa.addExpense("dinner", "Bela", 2_750_00,
new ExactSplit(map("Aman", 800_00L, "Bela", 650_00L, "Chirag", 700_00L, "Divya", 600_00L))),
goa.addExpense("scooters", "Chirag", 1_000_00, new PercentSplit(map("Aman", 40, "Chirag", 30, "Divya", 30))),
goa.addExpense("groceries", "Divya", 999_99, new ShareSplit(map("Aman", 2, "Bela", 1, "Chirag", 1, "Divya", 2))),
goa.addExpense("airport cab", "Aman", 100_00, new EqualSplit(List.of("Bela", "Chirag", "Divya"))));
for (Expense e : added) {
StringJoiner sj = new StringJoiner(", ");
e.owed().forEach((p, s) -> sj.add(p + " " + rs(s)));
System.out.println(String.format(" #%d %-11s %11s paid by %-6s -> %s", e.id(), e.description(), rs(e.amount()), e.paidBy(), sj));
}
System.out.println("\n2) Bad input is refused before anything is recorded");
Object[][] bad = {
{"dinner", "Bela", 2_750_00L, new ExactSplit(map("Aman", 800_00L, "Bela", 650_00L, "Chirag", 700_00L, "Divya", 550_00L))},
{"scooters", "Chirag", 1_000_00L, new PercentSplit(map("Aman", 40, "Chirag", 30, "Divya", 20))},
{"parasailing", "Esha", 3_000_00L, new EqualSplit()},
{"snacks", "Aman", 300_00L, new EqualSplit(List.of("Aman", "Farhan"))},
};
for (Object[] a : bad) {
try { goa.addExpense((String) a[0], (String) a[1], (Long) a[2], (Split) a[3]); }
catch (SplitError e) { System.out.println(String.format(" %-11s refused: %s", a[0], e.getMessage())); }
}
System.out.println(" expenses recorded: " + goa.expenses.size());
System.out.println("\n3) Net balance per person (+ is owed to them)");
showNet(goa);
System.out.println("\n4) Who owes whom, unsimplified: " + goa.pairwise().size() + " debts");
showPlan(goa.pairwise());
System.out.println(" Simplified: " + greedyPlan(goa.net).size() + " transfers");
showPlan(greedyPlan(goa.net));
System.out.println("\n5) Chirag settles, then the cab is deleted");
goa.settle("Chirag", "Aman", 2_600_00);
Expense removed = goa.delete(5);
System.out.println(" recorded payment Chirag -> Aman Rs 2600.00, deleted #" + removed.id() + " " + removed.description());
showNet(goa);
showPlan(greedyPlan(goa.net));
System.out.println("\n6) Greedy is not always the fewest transfers");
LinkedHashMap<String, Long> trip = map("Aman", -900_00L, "Bela", -800_00L, "Chirag", -500_00L,
"Divya", 700_00L, "Esha", 700_00L, "Farhan", 800_00L);
List<Transfer> g = greedyPlan(trip), best = minimumPlan(trip);
System.out.println(" greedy: " + g.size() + " transfers");
showPlan(g);
System.out.println(" minimum: " + best.size() + " transfers");
showPlan(best);
System.out.println("\n7) Eight threads add 100 expenses each to one group");
Group flat = new Group("Flat 4B", List.of("Aman", "Bela", "Chirag", "Divya"));
List<Thread> threads = new ArrayList<>();
for (int t = 0; t < 8; t++) {
final int n = t;
threads.add(new Thread(() -> {
String payer = flat.members.get(n % 4);
for (int i = 0; i < 100; i++) flat.addExpense("chai", payer, 10_00 + n, new EqualSplit());
}));
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
List<Integer> ids = new ArrayList<>(flat.expenses.keySet());
Collections.sort(ids);
long sum = flat.net.values().stream().mapToLong(Long::longValue).sum();
System.out.println(" " + flat.expenses.size() + " expenses, ids " + ids.get(0) + ".." + ids.get(ids.size() - 1)
+ ", balances sum to " + rs(sum));
showNet(flat);
}
}
Output
1) Five expenses, four split types
#1 hotel Rs 12000.00 paid by Aman -> Aman Rs 3000.00, Bela Rs 3000.00, Chirag Rs 3000.00, Divya Rs 3000.00
#2 dinner Rs 2750.00 paid by Bela -> Aman Rs 800.00, Bela Rs 650.00, Chirag Rs 700.00, Divya Rs 600.00
#3 scooters Rs 1000.00 paid by Chirag -> Aman Rs 400.00, Chirag Rs 300.00, Divya Rs 300.00
#4 groceries Rs 999.99 paid by Divya -> Aman Rs 333.33, Bela Rs 166.67, Chirag Rs 166.66, Divya Rs 333.33
#5 airport cab Rs 100.00 paid by Aman -> Bela Rs 33.34, Chirag Rs 33.33, Divya Rs 33.33
2) Bad input is refused before anything is recorded
dinner refused: exact amounts add up to Rs 2700.00, expense is Rs 2750.00
scooters refused: percentages add up to 90, not 100
parasailing refused: Esha is not in Goa trip
snacks refused: Farhan is not in Goa trip
expenses recorded: 5
3) Net balance per person (+ is owed to them)
Aman Rs 7566.67
Bela -Rs 1100.01
Chirag -Rs 3199.99
Divya -Rs 3266.67
4) Who owes whom, unsimplified: 6 debts
Bela pays Aman Rs 2233.34
Chirag pays Aman Rs 2633.33
Divya pays Aman Rs 2700.00
Chirag pays Bela Rs 700.00
Divya pays Bela Rs 433.33
Divya pays Chirag Rs 133.34
Simplified: 3 transfers
Divya pays Aman Rs 3266.67
Chirag pays Aman Rs 3199.99
Bela pays Aman Rs 1100.01
5) Chirag settles, then the cab is deleted
recorded payment Chirag -> Aman Rs 2600.00, deleted #5 airport cab
Aman Rs 4866.67
Bela -Rs 1066.67
Chirag -Rs 566.66
Divya -Rs 3233.34
Divya pays Aman Rs 3233.34
Bela pays Aman Rs 1066.67
Chirag pays Aman Rs 566.66
6) Greedy is not always the fewest transfers
greedy: 5 transfers
Aman pays Farhan Rs 800.00
Bela pays Divya Rs 700.00
Chirag pays Esha Rs 500.00
Aman pays Esha Rs 100.00
Bela pays Esha Rs 100.00
minimum: 4 transfers
Bela pays Farhan Rs 800.00
Aman pays Esha Rs 700.00
Chirag pays Divya Rs 500.00
Aman pays Divya Rs 200.00
7) Eight threads add 100 expenses each to one group
800 expenses, ids 1..800, balances sum to Rs 0.00
Aman -Rs 6.00
Bela -Rs 2.00
Chirag Rs 2.00
Divya Rs 6.00
Reading it:
- Demo 1 shows each split type and the rounding: ₹999.99 by shares gives Bela ₹166.67 and Chirag ₹166.66, and the ₹100 cab gives Bela ₹33.34. Every line sums to its expense.
- Demo 2: an exact split that is ₹50 short, percentages adding to 90, a payer who is not in the group and a participant who is not in the group are all refused, and the group still has exactly 5 expenses.
- Demo 3: Aman paid ₹12,100 (hotel plus cab) and his own shares were ₹3,000 + ₹800 + ₹400 + ₹333.33 = ₹4,533.33, so he is owed ₹7,566.67. The four balances sum to zero.
- Demo 4: 6 pairwise debts collapse to 3 transfers, all to Aman.
- Demo 5: Chirag pays Aman ₹2,600, then the cab is deleted. Chirag goes from −₹3,199.99 to −₹599.99 with the payment, then to −₹566.66 when his ₹33.33 share of the cab is removed. The plan is recomputed from the new balances; nothing about the old plan was stored.
- Demo 6: the six-person case, 5 transfers with greedy and 4 with the exact search.
- Demo 7: 800 expenses from 8 threads, ids 1 to 800 with no gaps or duplicates, balances summing to ₹0.00.
Follow-ups
“Two people add an expense to the same group at the same moment.” The id counter, the expense map and the balance map have to change together. That is the lock in _record. To check it matters, I removed the lock from the Java version and ran demo 7 five times. Every run crashed: the LinkedHashMap’s own size counter came out at 754 to 762 instead of 800, and listing its keys threw an exception, because concurrent inserts had corrupted the map itself. Lost balance updates would have been the quieter failure. In a database the same thing is one transaction that inserts the expense row and updates the members’ balance rows, or no balance rows at all and a SUM over the expense shares when the group is opened. Lock per group, never globally: two unrelated flats should not wait for each other.
“Someone taps Add twice on a slow network.” Make expense creation idempotent. The phone generates a request id when the user opens the form and sends it with every retry; the server stores it with the expense under a unique constraint and returns the existing expense if it sees the id again. Without it you get two ₹12,000 hotel entries, and the group finds out a week later.
“Edit an expense.” Delete and re-add under the same lock, so nobody sees the half-way state. Keep the old version for the activity feed (“Aman changed hotel from ₹12,000 to ₹11,500”), which you get for free if deletion is a soft delete with a timestamp rather than removal.
“Several people paid for one expense.” Replace paid_by with a paid: dict[str, int] that must sum to the amount, and _apply credits each payer their part. The net-balance view does not change at all. The pairwise view does: a share is now owed to several payers in proportion to what they paid, which needs allocate again.
“Multiple currencies.” Store each expense in its own currency and keep balances per (member, currency). Do not convert at write time; exchange rates change, and a ₹ balance computed from a $ expense at last month’s rate will not match what anyone expects. Convert only when settling, at a rate the user sees and accepts.
“A group of 5,000 people.” The exact minimum is out (2⁵⁰⁰⁰ subsets). Greedy with two heaps is O(n log n). Net balances should be stored rather than recomputed from millions of expenses on every page load, which is what the cache in this design already is.
“Show me my balance across all groups.” Sum the member’s net balance over every group they are in, which needs an index from member to groups. Do not simplify across groups unless the users agreed to it: money from the flat and money from the Goa trip are often settled with different people.
Common mistakes
floatordoublefor amounts. Balances stop summing to zero and the app shows “you owe ₹0.00” in red.- Rounding each share independently. Three shares of ₹33.33 for a ₹100 expense lose a paisa. Allocate the remainder explicitly.
- Storing percentages instead of resolved amounts. Then the amounts people saw can change if the rounding code changes.
- Only a pairwise ledger, no expense list. Edits and deletes become a careful undo of scattered updates, and when it drifts there is nothing to rebuild from.
- Validating after writing. An exact split that is ₹50 short must be refused before the expense gets an id and touches any balance.
- Calling greedy simplification optimal. It is at most n − 1 transfers, not the minimum. Have the −₹900, −₹800, −₹500, +₹700, +₹700, +₹800 example ready, or make your own.
- A
SplitFactorywith a string switch inside the model. Parsing belongs at the API edge. - Simplifying without asking. Some groups want to see “I owe Chirag” literally. Keep the raw view.
The next case study, the library management system, has no money puzzle at its centre. Its hard parts are a queue of people waiting for one title, a hold shelf that expires, and the difference between a book and a copy of it.
Key takeaways
- Expenses are the source of truth and are immutable; net balances are a cache that always sums to zero.
- Money is integer paise. Proportional splits use the largest remainder method so shares add up exactly.
- Split types are strategies that return resolved paise and validate their own input.
- Greedy settle-up needs at most n − 1 transfers and is the right default. The true minimum is n minus the largest number of zero-sum groups, NP-hard in general, easy for a group of friends.
- Lock per group around id, insert and balance update; make creation idempotent with a client request id.
Exercises
- Add multi-payer expenses:
paidbecomes a map that must sum to the amount. Update_applyandpairwise, then rewrite the Goa dinner as “Bela paid ₹2,000, Aman paid ₹750”. Before running it, work out how Aman’s and Bela’s balances should move, and check that the four still sum to zero. - Add a cheap improvement to
greedy_plan: before the main loop, settle every debtor whose balance is the exact opposite of some creditor’s. Rerun the 10,000-group experiment. How many of the 916 cases does it fix? - Implement
edit(expense_id, new_amount, new_split)as delete plus add under one lock acquisition, and keep the old version in a history list. - Change the remainder rule so the leftover paise go to the payer’s share if the payer is part of the split, and to the first listed otherwise. What changes in demo 1?
Quiz
- Why store the list of expenses and not only a pairwise
owes[a][b]ledger? - ₹1,000.00 is split by shares 1:1:1 among three people. What does each owe, in paise, with this code’s rule?
- Greedy settle-up gives at most how many transfers for n people with non-zero balances, and why?
- Balances are −₹300, −₹200, +₹200, +₹300. What is the minimum number of transfers, and does greedy find it?
- Why does
add_expensecall the split strategy before taking the group’s lock?
Show answers
- Edits and deletes are then “apply the expense with the opposite sign”, and if the cached balances are ever wrong they can be rebuilt from the list. A ledger alone has nothing to rebuild from.
- 100,000 / 3 is 33,333 each with 1 paisa left. All remainders tie, so the first listed pays 33,334 and the other two 33,333.
- n − 1. Each transfer moves the smaller of the two balances, so it brings at least one person to exactly zero, and the last transfer zeroes two people at once.
- Two: the −₹300 pays the +₹300 and the −₹200 pays the +₹200. Greedy finds it here, because the largest debtor and the largest creditor happen to be an exact pair.
- Resolving and validating a split does not touch shared state, so it does not need the lock. Keeping it outside means a rejected or slow request never blocks other people adding expenses to the same group.