Algo-Sim › Low-Level Design
Splitwise (expense sharing)
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
Record shared expenses as one net balance per user, then settle with a greedy match of the biggest debtor and the biggest creditor using two heaps.
Problem
Design an expense-sharing service for n users. expense(payer, amount) records that payer paid amount on behalf of everyone, split equally among all n users. balance(user) returns the user’s net balance (positive: others owe them). settle() pays everyone back with as few transfers as the greedy rule finds, the largest debtor paying the largest creditor each time (ties by smaller user id), returns the number of transfers and resets every balance to 0.
Constraints
- 2 ≤ n ≤ 10⁴; amounts are multiples of n
- expense O(n); balance O(1); settle O(n log n)
- The balances always sum to 0
Edge cases to test
- Everyone already settled
- One person owes everyone
- Rounding cents in a three-way split
Follow-up questions
- Is the greedy settlement minimal?
- It uses at most n − 1 transfers, but the true minimum is NP-hard (it depends on subsets that sum to zero); backtracking finds it for small groups (LC 465).
- How do you avoid rounding errors?
- Store amounts as integer cents and give leftover cents to specific people deterministically.
Solution
Java
class Splitwise {
private final int[] net; // net[u] > 0: u is owed money; < 0: u owes
public Splitwise(int n) {
net = new int[n + 1];
}
/** payer paid amount for everyone; each of the n users owes an equal share. */
public void expense(int payer, int amount) {
int share = amount / (net.length - 1);
for (int u = 1; u < net.length; u++) net[u] -= share;
net[payer] += amount;
}
public int balance(int user) {
return net[user];
}
/** Greedy: the biggest debtor pays the biggest creditor until all are even. */
public int settle() {
Comparator<int[]> biggest = (a, b) -> a[1] != b[1] ? Integer.compare(b[1], a[1]) : Integer.compare(a[0], b[0]);
PriorityQueue<int[]> owed = new PriorityQueue<>(biggest); // {user, amount}
PriorityQueue<int[]> owes = new PriorityQueue<>(biggest);
for (int u = 1; u < net.length; u++) {
if (net[u] > 0) owed.add(new int[] {u, net[u]});
else if (net[u] < 0) owes.add(new int[] {u, -net[u]});
}
int transfers = 0;
while (!owed.isEmpty()) {
int[] c = owed.poll(), d = owes.poll();
int x = Math.min(c[1], d[1]);
transfers++;
if (c[1] > x) owed.add(new int[] {c[0], c[1] - x});
if (d[1] > x) owes.add(new int[] {d[0], d[1] - x});
}
Arrays.fill(net, 0);
return transfers;
}
}Python
import heapq
class Splitwise:
def __init__(self, n):
self.net = [0] * (n + 1) # net[u] > 0: u is owed money; < 0: u owes
# payer paid amount for everyone; each of the n users owes an equal share.
def expense(self, payer, amount):
share = amount // (len(self.net) - 1)
for u in range(1, len(self.net)):
self.net[u] -= share
self.net[payer] += amount
def balance(self, user):
return self.net[user]
# Greedy: the biggest debtor pays the biggest creditor until all are even.
def settle(self):
owed, owes = [], [] # (-amount, user): biggest first
for u in range(1, len(self.net)):
if self.net[u] > 0:
heapq.heappush(owed, (-self.net[u], u))
elif self.net[u] < 0:
heapq.heappush(owes, (self.net[u], u))
transfers = 0
while owed:
c, cu = heapq.heappop(owed)
d, du = heapq.heappop(owes)
x = min(-c, -d)
transfers += 1
if -c > x:
heapq.heappush(owed, (c + x, cu))
if -d > x:
heapq.heappush(owes, (d + x, du))
self.net = [0] * len(self.net)
return transfersC++
#include <bits/stdc++.h>
using namespace std;
class Splitwise {
public:
vector<int> net; // net[u] > 0: u is owed money; < 0: u owes
Splitwise(int n) {
net = vector<int>(n + 1);
}
/** payer paid amount for everyone; each of the n users owes an equal share. */
void expense(int payer, int amount) {
int share = amount / (int(net.size()) - 1);
for (int u = 1; u < int(net.size()); u++)
net[u] -= share;
net[payer] += amount;
}
int balance(int user) {
return net[user];
}
/** Greedy: the biggest debtor pays the biggest creditor until all are even. */
int settle() {
auto biggest = [](const vector<int> &a, const vector<int> &b) { return a[1] != b[1] ? a[1] < b[1] : a[0] > b[0]; };
priority_queue<vector<int>, vector<vector<int>>, decltype(biggest)> owed(biggest), owes(biggest);
for (int u = 1; u < int(net.size()); u++) {
if (net[u] > 0)
owed.push(vector<int>{u, net[u]});
else if (net[u] < 0)
owes.push(vector<int>{u, -net[u]});
}
int transfers = 0;
while (!owed.empty()) {
auto c = owed.top();
owed.pop();
auto d = owes.top();
owes.pop();
int x = std::min(c[1], d[1]);
transfers++;
if (c[1] > x)
owed.push(vector<int>{c[0], c[1] - x});
if (d[1] > x)
owes.push(vector<int>{d[0], d[1] - x});
}
fill(net.begin(), net.end(), 0);
return transfers;
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)