SDE Path

Splitwise (Expense Sharing)

Hard

Splitwise (Expense Sharing)

Group-expense accounting with integer-exact splits and greedy debt simplification — the most finance-flavored LLD classic.

Requirements

  • All money is integer cents. Sum of all balances is always 0 — state this invariant and preserve it in every operation.
  • Split remainders deterministically: ⌊amount/k⌋ each, then the first amount mod k users in the participants list pay one extra cent.
  • The payer's balance rises by the full amount paid, then falls by their own share if they appear in the participants list.
  • simplify is a pure query — running it twice in a row returns the same number.

API to implement

Implement the class Splitwise. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.

| Command | Returns | Behavior | |---|---|---| | expense <payer> <amount> <participants> | — | payer paid amount (cents) split equally among participants — a comma-separated user list with no spaces (it may or may not include the payer). Integer split: each owes ⌊amount/k⌋; the leftover cents go +1 each to the earliest users in list order. | | balance <user> | long | Net balance of user in cents: positive means the group owes them, negative means they owe. Unknown users are 0. | | settle <fromUser> <toUser> <amount> | — | fromUser hands toUser amount cents in cash, adjusting both balances. | | simplify | int | Without changing any state, return how many transactions the greedy min-cash-flow algorithm needs to settle all debts: repeatedly match the largest creditor with the largest debtor (ties → lexicographically smaller user id) and settle min(credit, debt). |

Input format

The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.

Output format

For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.

This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.

Sample cases

Example 1
Input
10
expense alice 300 alice,bob,carol
balance alice
balance bob
expense bob 100 alice,carol
balance bob
balance carol
simplify
settle carol alice 50
balance carol
simplify
Expected output
200
-100
0
-150
1
-100
1
Example 2
Input
6
expense a 1000 b,c,d
balance a
balance b
balance c
balance d
simplify
Expected output
1000
-334
-333
-333
3