Group Expense Ledger and Minimum-Transfer Debt Settlement

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Design a group expense-tracking service and implement its debt-settlement engine. In a live interview, the problem spans two halves:

  1. System & API Design: Specify functional and non-functional requirements for recording shared bills among group participants, computing exact per-member balances in integer minor units (such as cents), serving read-only payout previews, and logging completed repayments with idempotency and auditability. Sketch the core storage entities (User, Group, Expense, ExpenseShare, Payment) and REST/service endpoints.
  2. Settlement Algorithms: Once historical bills and repayments are aggregated into each participant's net balance, implement settlement_plans(net_positions) to return both a fast baseline payout schedule ("settle") and a minimum-transfer payout schedule ("settle_optimally").
def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]:

Rules & Output Contract

  • net_positions maps each participant's name (str) to an integer balance (int):
    • A positive value means the participant is owed that amount overall (creditor).
    • A negative value means the participant owes that amount overall (debtor).
    • A zero value means the participant is already even and must not appear in any transfer.
  • Conservation check: If the values in net_positions do not sum to 0, raise ValueError. Do not mutate net_positions.
  • Return a dictionary with two keys, "settle" and "settle_optimally", each mapping to {"transactions": [[payer, payee, amount], ...], "count": int}:
    • "settle" runs a single two-pointer sweep across all non-zero debtors and creditors in their appearance order in net_positions, transferring min(remaining_debt, remaining_credit) at each step (producing at most n - 1 transfers for n non-zero participants).
    • "settle_optimally" clears every balance using the strictly minimum possible number of transfers (n - G, where G is the maximum number of disjoint zero-sum subsets into which the n non-zero participants can be partitioned). Order non-zero participants to maximize zero-sum prefixes (breaking bitmask DP ties toward smaller participant indices), sort each resulting zero-sum group by input appearance order, and run the two-pointer sweep within each group.
    • In both plans, each transfer [payer, payee, amount] has amount > 0 and payer != payee, and "transactions" is sorted by (payer, payee) using the participants' appearance order in net_positions.

Examples

Example 1

Input: net_positions = {"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}
Output:
{
  "settle": {
    "transactions": [["Nora", "Maya", 15], ["Owen", "Maya", 20], ["Owen", "Leo", 15]],
    "count": 3
  },
  "settle_optimally": {
    "transactions": [["Nora", "Leo", 15], ["Owen", "Maya", 35]],
    "count": 2
  }
}

Walk-through: Pairing debtors [Nora: 15, Owen: 35] against creditors [Maya: 35, Leo: 15] front-to-back sends 15 from Nora to Maya, leaving Maya owed 20 and causing Owen to split payments across Maya (20) and Leo (15) for 3 transfers total. Partitioning into the two independent zero-sum pairs {Leo: +15, Nora: -15} and {Maya: +35, Owen: -35} settles everyone in 4 - 2 = 2 transfers.

Example 2

Input: net_positions = {"Eli": -25, "Zoe": 0, "Kai": 25}
Output:
{
  "settle": {"transactions": [["Eli", "Kai", 25]], "count": 1},
  "settle_optimally": {"transactions": [["Eli", "Kai", 25]], "count": 1}
}

Walk-through: Zoe already has a 0 balance and is excluded. Eli pays Kai 25 in 1 transfer under both strategies.

Example 3

Input: net_positions = {"Aria": -12, "Ben": -18, "Chloe": 30}
Output:
{
  "settle": {"transactions": [["Aria", "Chloe", 12], ["Ben", "Chloe", 18]], "count": 2},
  "settle_optimally": {"transactions": [["Aria", "Chloe", 12], ["Ben", "Chloe", 18]], "count": 2}
}

Walk-through: No proper non-empty subset sums to 0, so G = 1 and at least 3 - 1 = 2 transfers are required. Both Aria and Ben pay Chloe directly.

Example 4

Input: net_positions = {"Sam": 0, "Tara": 0, "Uma": 0}
Output:
{
  "settle": {"transactions": [], "count": 0},
  "settle_optimally": {"transactions": [], "count": 0}
}

Walk-through: Every participant is already settled, so zero transfers are needed.

Constraints

  • 0 <= n <= 20, where n is the number of participants with a non-zero balance in net_positions.
  • All balances are integers representing minor currency units (-10^9 <= balance <= 10^9).
  • A valid input satisfies sum(net_positions.values()) == 0; otherwise settlement_plans must raise ValueError.
  • Calling settlement_plans must leave the input net_positions dictionary unchanged.

Step-by-step walkthrough

  1. Understand the problem and output contract

    This interview spans two halves: designing a group expense-tracking service and implementing its settlement engine settlement_plans(net_positions).

    In the coding half, all historical bills and repayments have already been aggregated into net_positions, a dictionary mapping each participant to an integer net balance in minor currency units (such as cents):

    • Positive (+35): the group owes this participant 35 units overall (a creditor).
    • Negative (-15): this participant owes the group 15 units overall (a debtor).
    • Zero (0): this participant is already completely even.
    • Because every split share belongs to someone in the group, all net balances must sum to 0.

    We must return a dictionary containing two valid payout schedules:

    {
      "settle":           {"transactions": [[payer, payee, amount], ...], "count": k1},
      "settle_optimally": {"transactions": [[payer, payee, amount], ...], "count": k2},
    }
    
    • settle clears everyone's balance quickly (using at most n - 1 transfers for n non-zero participants).
    • settle_optimally clears everyone's balance using the strictly minimum possible number of transfers.
    • To produce a deterministic output order, we preserve the input dictionary's participant order when pairing debtors with creditors, and sort finished transfers by (payer, payee) in that input order.
  2. Design context: from raw bills to net balances

    Before writing code, let's anchor the system and API half concisely so you can present a crisp design discussion in an interview:

    Core tables (source of truth — all money stored as integer cents, never floats):
      User(id, name)
      Group(id, name)                 GroupMember(group_id, user_id)
      Expense(id, group_id, paid_by, amount_cents, currency, split_type, version, idempotency_key)
      ExpenseShare(expense_id, user_id, share_cents)    -- exact cent shares summing to amount_cents
      Payment(id, group_id, payer, payee, amount_cents, idempotency_key)  -- append-only real transfers
    
    Derived net balance for participant m:
      net(m) = sum(expenses m paid) - sum(m's ExpenseShares)
             + sum(payments m sent) - sum(payments m received)
    
    Core API endpoints:
      POST /groups/{g}/expenses                 -- create expense + shares (with idempotency_key)
      PUT  /groups/{g}/expenses/{id}            -- edit expense (with expected_version)
      GET  /groups/{g}/balances                 -- returns {member: net_cents}
      GET  /groups/{g}/settlement?optimal=true  -- pure read preview; never mutates balances!
      POST /groups/{g}/payments                 -- record an actual repayment
    

    Four non-functional rules protect real money:

    1. Integer minor units everywhere: 0.1 + 0.2 != 0.3 in binary floating point; storing integer cents and assigning remainder cents deterministically (e.g., 1000 cents split 3 ways -> 334, 333, 333 cents) keeps the group sum at 0.
    2. Source of truth vs. derived state: Bills, split shares, and repayments are immutable/versioned facts; balances are derived from them so editing a bill never corrupts history.
    3. Idempotent writes and optimistic locking: An idempotency key (a unique client-generated ID per request) prevents network retries from double-recording a write, and expected_version (optimistic concurrency control) prevents two simultaneous edits from silently overwriting each other.
    4. Preview vs. recorded repayment: Requesting a payout schedule is a read-only suggestion; balances change only when a Payment record is written. Out of scope: direct bank rails, cross-currency FX brokerage, and authentication.
  3. Fast baseline (`settle`): two-pointer sweep across debtors and creditors

    Do payout transfers have to replay every grocery or fuel receipt backward? No! Money is fungible: as long as every debtor sends their exact negative balance and every creditor receives their exact positive balance, everyone ends at 0.

    That gives a fast, clean two-pointer sweep for _greedy_payments:

    1. Collect all debtors (amount < 0, storing +abs(amount) left to pay) and all creditors (amount > 0, storing amount left to receive).
    2. Point debtor_ptr at the first debtor and creditor_ptr at the first creditor.
    3. Transfer min(still_owes, still_owed) from that debtor to that creditor.
    4. Subtract transfer from both, and advance whichever pointer (or both!) hits 0.
    Example: debtors = [[Nora, 15], [Owen, 35]], creditors = [[Maya, 35], [Leo, 15]]
    
    Step 1: Nora owes 15, Maya is owed 35 -> Nora pays Maya 15 (Nora hits 0 -> advance debtor_ptr; Maya has 20 left)
    Step 2: Owen owes 35, Maya is owed 20 -> Owen pays Maya 20 (Maya hits 0 -> advance creditor_ptr; Owen has 15 left)
    Step 3: Owen owes 15, Leo is owed 15  -> Owen pays Leo 15  (BOTH hit 0 -> advance both; done!)
    

    Why does this take at most k - 1 transfers for k non-zero participants? Every transfer reduces at least one person's remaining balance to 0, and because total debt equals total credit, the final transfer always clears two people simultaneously.

    def _greedy_payments(amounts: List[int], members: List[int]) -> List[Tuple[int, int, int]]:
        """Settle `members` (indices into `amounts`, whose balances sum to zero) using two pointers.
    
        Returns (payer_idx, payee_idx, amount_cents) triples in at most len(members) - 1 payments.
        """
        # debtors: list of [member_idx, cents_still_to_pay], e.g. [[2, 15], [3, 35]]
        debtors: List[List[int]] = []
        # creditors: list of [member_idx, cents_still_to_receive], e.g. [[0, 35], [1, 15]]
        creditors: List[List[int]] = []
    
        for member_idx in members:
            if amounts[member_idx] < 0:
                debtors.append([member_idx, -amounts[member_idx]])
            elif amounts[member_idx] > 0:
                creditors.append([member_idx, amounts[member_idx]])
    
        payments: List[Tuple[int, int, int]] = []
        debtor_ptr = 0
        creditor_ptr = 0
    
        # Pair the current debtor and current creditor until both lists run out together.
        while debtor_ptr < len(debtors) and creditor_ptr < len(creditors):
            payer_idx, still_owes = debtors[debtor_ptr]
            payee_idx, still_owed = creditors[creditor_ptr]
    
            # Transfer whichever side needs less so nobody ever overshoots zero.
            transfer = min(still_owes, still_owed)
            payments.append((payer_idx, payee_idx, transfer))
    
            debtors[debtor_ptr][1] -= transfer
            creditors[creditor_ptr][1] -= transfer
    
            # Advance BOTH pointers if a tie cleared both sides at once (avoids 0-cent payments).
            if debtors[debtor_ptr][1] == 0:
                debtor_ptr += 1
            if creditors[creditor_ptr][1] == 0:
                creditor_ptr += 1
    
        return payments
    
    
    def _format_plan(payments: List[Tuple[int, int, int]], names: List[str]) -> Dict[str, object]:
        """Convert index triples to [payer_name, payee_name, amount] sorted by payer then payee."""
        transactions: List[List[object]] = []
        for payer_idx, payee_idx, amount in sorted(payments):
            transactions.append([names[payer_idx], names[payee_idx], amount])
        return {"transactions": transactions, "count": len(transactions)}
    
  4. Exact minimum (`settle_optimally`): why the minimum is `n - G`

    Look at why the sweep needed 3 transfers on {"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35} when 2 were enough: Nora (-15) paid Maya (+35) first, entangling {Maya, Owen} with {Leo, Nora}! Had we kept {Maya: +35, Owen: -35} and {Leo: +15, Nora: -15} as two separate zero-sum groups, each group of 2 would have settled in 2 - 1 = 1 transfer (2 total).

    Let's prove that for n non-zero participants, the minimum number of transfers is always n - G, where G is the maximum number of disjoint zero-sum subsets the n participants can be partitioned into:

     Greedy sweep (1 group of 4 -> 4 - 1 = 3 edges)       Optimal split (2 groups of 2 -> 4 - 2 = 2 edges)
         Nora(-15) ----15----> Maya(+35)                      Nora(-15) ----15----> Leo(+15)
                                  ^
                                  | 20                        Owen(-35) ----35----> Maya(+35)
         Owen(-35) ----15----> Leo(+15)
    
    1. No plan can beat n - G (lower bound): Draw the n non-zero participants as dots and each transfer in any valid plan as a line between two dots. Look at the connected components (isolated islands of dots linked by transfers). Because no money crosses between different islands and everyone ends at 0, the starting balances inside each island must already add up to 0! If there are c islands of sizes s_1, ..., s_c, connecting s_i dots takes at least s_i - 1 lines, so total transfers >= (s_1 - 1) + ... + (s_c - 1) = n - c. Since c cannot exceed the maximum possible number of zero-sum subsets G, every valid plan uses at least n - G transfers.
    2. We can always achieve n - G (upper bound): Partition the n participants into G zero-sum groups and run _greedy_payments inside each group. Each group i uses at most s_i - 1 transfers, summing to at most n - G (and therefore exactly n - G)!

    Notice that testing whether G >= 2 ("does any non-empty proper subset sum to zero?") is the classic subset-sum problem (which is NP-complete, meaning no known polynomial-time algorithm solves all cases). That tells us an O(n * 2^n) exact algorithm is the right tool for typical groups up to ~20 participants.

  5. Finding `G` with bitmask dynamic programming

    How do we find the best partition into zero-sum subsets in O(n * 2^n) time?

    Imagine lining up the n participants in some left-to-right order and counting how many prefixes (first 1 person, first 2 people, ..., all n people) sum to 0:

    Order:       [ Nora(-15),  Leo(+15),  Owen(-35),  Maya(+35) ]
    Prefix sum:      -15          0          -35          0
                                  ^                       ^
                              cut here!               cut here!  -> 2 zero-sum groups: {Leo, Nora} and {Maya, Owen}
    

    Whenever a prefix sums to 0, the slice since the previous 0 prefix also sums to 0 (0 - 0 = 0)! Conversely, concatenating G zero-sum groups side by side creates an ordering with at least G zero-sum prefixes. So maximizing zero-sum groups is identical to finding a participant ordering with the most zero-sum prefixes.

    To search over subsets instead of all n! permutations, we represent each subset of {0, ..., n - 1} as a bitmask — an integer from 0 to 2^n - 1 whose i-th binary bit (1 << i) is 1 if participant i is in the subset and 0 if not:

    n = 4 (bit 0=Maya, bit 1=Leo, bit 2=Nora, bit 3=Owen):
      mask = 6  (binary 0110) -> subset {Leo, Nora},       subset_sum[6]  = +15 + (-15) = 0
      mask = 15 (binary 1111) -> subset {Maya,Leo,Nora,Owen}, subset_sum[15] = 0
    

    For each non-empty mask, if participant i is placed last among mask's members, the earlier prefixes come from prev_mask = mask ^ (1 << i) (mask with bit i turned off), plus 1 extra zero-sum prefix if subset_sum[mask] == 0:

    best_groups[mask] = max over (i in mask) of best_groups[mask ^ (1 << i)]
                      + (1 if subset_sum[mask] == 0 else 0)
    

    Remembering which i won in last_member[mask] lets us walk backward from full_mask to 0 to recover the exact optimal ordering, then cut whenever the running sum hits 0.

  6. Code `_max_zero_sum_groups` and `settlement_plans`

    Notice how we also build subset_sum cleanly without cryptic bit tricks: adding participant member_idx (member_bit = 1 << member_idx) to every already-computed prev_mask < member_bit fills all 2^n subset sums in O(2^n) additions.

    def _max_zero_sum_groups(amounts: List[int]) -> List[List[int]]:
        """Partition `0 .. len(amounts) - 1` into the maximum number of disjoint zero-sum subsets."""
        n = len(amounts)
        if n == 0:
            return []
    
        num_masks = 1 << n
        full_mask = num_masks - 1
    
        # Phase 1: Precompute subset_sum[mask] = sum of balances for members whose bit is 1 in `mask`.
        subset_sum = [0] * num_masks
        for member_idx in range(n):
            member_bit = 1 << member_idx
            for prev_mask in range(member_bit):
                subset_sum[prev_mask | member_bit] = subset_sum[prev_mask] + amounts[member_idx]
    
        # Phase 2: Bitmask DP over subset orderings.
        # best_groups[mask] = maximum number of zero-sum prefixes achievable by ordering `mask`.
        # last_member[mask] = which member sits at the end of `mask` in that best ordering.
        best_groups = [0] * num_masks
        last_member = [-1] * num_masks
    
        for mask in range(1, num_masks):
            best_prev = -1
            chosen_member = -1
            for member_idx in range(n):
                member_bit = 1 << member_idx
                if mask & member_bit:
                    prev_mask = mask ^ member_bit
                    if best_groups[prev_mask] > best_prev:
                        best_prev = best_groups[prev_mask]
                        chosen_member = member_idx
    
            # If `mask` itself sums to zero, completing `mask` finishes one more zero-sum group.
            if subset_sum[mask] == 0:
                best_groups[mask] = best_prev + 1
            else:
                best_groups[mask] = best_prev
            last_member[mask] = chosen_member
    
        # Phase 3: Reconstruct the member ordering from full_mask back to 0, then reverse it.
        order: List[int] = []
        mask = full_mask
        while mask > 0:
            member_idx = last_member[mask]
            order.append(member_idx)
            mask ^= 1 << member_idx
        order.reverse()
    
        # Phase 4: Cut `order` every time the running prefix sum hits zero.
        # Because previous groups summed to 0, each cut slice also sums to 0 on its own.
        groups: List[List[int]] = []
        current_group: List[int] = []
        running_sum = 0
        for member_idx in order:
            current_group.append(member_idx)
            running_sum += amounts[member_idx]
            if running_sum == 0:
                # Sort indices so _greedy_payments processes members in original input order.
                groups.append(sorted(current_group))
                current_group = []
    
        return groups
    

    Finally, settlement_plans filters out 0-balance participants, validates sum(amounts) == 0, runs _greedy_payments once on everyone for settle, and runs _greedy_payments on each zero-sum group for settle_optimally — never mutating the caller's net_positions dictionary.

    def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]:
        # Filter out settled members (balance == 0) while preserving input order for tie-breaking.
        names: List[str] = []
        amounts: List[int] = []
        for name, amount in net_positions.items():
            if amount != 0:
                names.append(name)
                amounts.append(amount)
    
        # Conservation of money: every cent owed by someone must be owed to someone else.
        if sum(amounts) != 0:
            raise ValueError("net positions must sum to zero")
    
        # Plan 1 (settle): single greedy sweep across all non-zero members (at most n - 1 payments).
        all_members = list(range(len(names)))
        simple_payments = _greedy_payments(amounts, all_members)
    
        # Plan 2 (settle_optimally): partition into G zero-sum groups and sweep each (n - G payments).
        optimal_payments: List[Tuple[int, int, int]] = []
        for group in _max_zero_sum_groups(amounts):
            optimal_payments.extend(_greedy_payments(amounts, group))
    
        return {
            "settle": _format_plan(simple_payments, names),
            "settle_optimally": _format_plan(optimal_payments, names),
        }
    
  7. Walk through Example 1 end to end

    Input: {"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35} -> names = ["Maya", "Leo", "Nora", "Owen"], amounts = [35, 15, -15, -35].

    1. settle (all_members = [0, 1, 2, 3]):
       debtors = [[2(Nora), 15], [3(Owen), 35]],  creditors = [[0(Maya), 35], [1(Leo), 15]]
       - Nora pays Maya 15 -> Nora=0 (next debtor), Maya=20
       - Owen pays Maya 20 -> Owen=15, Maya=0 (next creditor)
       - Owen pays Leo 15  -> Owen=0, Leo=0 (done)
       Result: [["Nora", "Maya", 15], ["Owen", "Maya", 20], ["Owen", "Leo", 15]], count = 3
    
    2. settle_optimally:
       Zero-sum masks: mask 6 ({Leo, Nora}), mask 9 ({Maya, Owen}), mask 15 ({Maya, Leo, Nora, Owen})
       best_groups[15] = 2 -> groups = [[1, 2], [0, 3]] ({Leo, Nora} and {Maya, Owen})
       - Sweep {Leo, Nora}:  Nora pays Leo 15
       - Sweep {Maya, Owen}: Owen pays Maya 35
       Sorted by (payer_idx, payee_idx): [["Nora", "Leo", 15], ["Owen", "Maya", 35]], count = 4 - 2 = 2
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _greedy_payments(amounts: List[int], members: List[int]) -> List[Tuple[int, int, int]]:
        """Settle `members` (indices into `amounts`, whose balances sum to zero) using two pointers.
    
        Returns (payer_idx, payee_idx, amount_cents) triples in at most len(members) - 1 payments.
        """
        # debtors: list of [member_idx, cents_still_to_pay], e.g. [[2, 15], [3, 35]]
        debtors: List[List[int]] = []
        # creditors: list of [member_idx, cents_still_to_receive], e.g. [[0, 35], [1, 15]]
        creditors: List[List[int]] = []
    
        for member_idx in members:
            if amounts[member_idx] < 0:
                debtors.append([member_idx, -amounts[member_idx]])
            elif amounts[member_idx] > 0:
                creditors.append([member_idx, amounts[member_idx]])
    
        payments: List[Tuple[int, int, int]] = []
        debtor_ptr = 0
        creditor_ptr = 0
    
        # Pair the current debtor and current creditor until both lists run out together.
        while debtor_ptr < len(debtors) and creditor_ptr < len(creditors):
            payer_idx, still_owes = debtors[debtor_ptr]
            payee_idx, still_owed = creditors[creditor_ptr]
    
            # Transfer whichever side needs less so nobody ever overshoots zero.
            transfer = min(still_owes, still_owed)
            payments.append((payer_idx, payee_idx, transfer))
    
            debtors[debtor_ptr][1] -= transfer
            creditors[creditor_ptr][1] -= transfer
    
            # Advance BOTH pointers if a tie cleared both sides at once (avoids 0-cent payments).
            if debtors[debtor_ptr][1] == 0:
                debtor_ptr += 1
            if creditors[creditor_ptr][1] == 0:
                creditor_ptr += 1
    
        return payments
    
    
    def _max_zero_sum_groups(amounts: List[int]) -> List[List[int]]:
        """Partition `0 .. len(amounts) - 1` into the maximum number of disjoint zero-sum subsets."""
        n = len(amounts)
        if n == 0:
            return []
    
        num_masks = 1 << n
        full_mask = num_masks - 1
    
        # Phase 1: Precompute subset_sum[mask] = sum of balances for members whose bit is 1 in `mask`.
        subset_sum = [0] * num_masks
        for member_idx in range(n):
            member_bit = 1 << member_idx
            for prev_mask in range(member_bit):
                subset_sum[prev_mask | member_bit] = subset_sum[prev_mask] + amounts[member_idx]
    
        # Phase 2: Bitmask DP over subset orderings.
        # best_groups[mask] = maximum number of zero-sum prefixes achievable by ordering `mask`.
        # last_member[mask] = which member sits at the end of `mask` in that best ordering.
        best_groups = [0] * num_masks
        last_member = [-1] * num_masks
    
        for mask in range(1, num_masks):
            best_prev = -1
            chosen_member = -1
            for member_idx in range(n):
                member_bit = 1 << member_idx
                if mask & member_bit:
                    prev_mask = mask ^ member_bit
                    if best_groups[prev_mask] > best_prev:
                        best_prev = best_groups[prev_mask]
                        chosen_member = member_idx
    
            # If `mask` itself sums to zero, completing `mask` finishes one more zero-sum group.
            if subset_sum[mask] == 0:
                best_groups[mask] = best_prev + 1
            else:
                best_groups[mask] = best_prev
            last_member[mask] = chosen_member
    
        # Phase 3: Reconstruct the member ordering from full_mask back to 0, then reverse it.
        order: List[int] = []
        mask = full_mask
        while mask > 0:
            member_idx = last_member[mask]
            order.append(member_idx)
            mask ^= 1 << member_idx
        order.reverse()
    
        # Phase 4: Cut `order` every time the running prefix sum hits zero.
        # Because previous groups summed to 0, each cut slice also sums to 0 on its own.
        groups: List[List[int]] = []
        current_group: List[int] = []
        running_sum = 0
        for member_idx in order:
            current_group.append(member_idx)
            running_sum += amounts[member_idx]
            if running_sum == 0:
                # Sort indices so _greedy_payments processes members in original input order.
                groups.append(sorted(current_group))
                current_group = []
    
        return groups
    
    
    def _format_plan(payments: List[Tuple[int, int, int]], names: List[str]) -> Dict[str, object]:
        """Convert index triples to [payer_name, payee_name, amount] sorted by payer then payee."""
        transactions: List[List[object]] = []
        for payer_idx, payee_idx, amount in sorted(payments):
            transactions.append([names[payer_idx], names[payee_idx], amount])
        return {"transactions": transactions, "count": len(transactions)}
    
    
    def settlement_plans(net_positions: Dict[str, int]) -> Dict[str, object]:
        # Filter out settled members (balance == 0) while preserving input order for tie-breaking.
        names: List[str] = []
        amounts: List[int] = []
        for name, amount in net_positions.items():
            if amount != 0:
                names.append(name)
                amounts.append(amount)
    
        # Conservation of money: every cent owed by someone must be owed to someone else.
        if sum(amounts) != 0:
            raise ValueError("net positions must sum to zero")
    
        # Plan 1 (settle): single greedy sweep across all non-zero members (at most n - 1 payments).
        all_members = list(range(len(names)))
        simple_payments = _greedy_payments(amounts, all_members)
    
        # Plan 2 (settle_optimally): partition into G zero-sum groups and sweep each (n - G payments).
        optimal_payments: List[Tuple[int, int, int]] = []
        for group in _max_zero_sum_groups(amounts):
            optimal_payments.extend(_greedy_payments(amounts, group))
    
        return {
            "settle": _format_plan(simple_payments, names),
            "settle_optimally": _format_plan(optimal_payments, names),
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine four teammates reconciling shared cabin, grocery, and fuel bills at the end of a trip. Rather than reimbursing every individual receipt one by one, each person writes a single integer on an index card: their net balance (total cents owed to them if positive, or owed by them overall if negative — all cards always add up to 0). Once we work with net balances, any debtor can pay any creditor. For settle, we line up debtors on the left and creditors on the right and pair them front-to-back in at most n - 1 transfers. For settle_optimally, we notice that every independent mini-cluster whose cards already cancel out to 0 saves one whole transfer: partitioning n non-zero people into G disjoint zero-sum subsets lets us clear everyone in n - G transfers — and viewing transfers as graph edges proves no valid plan can ever do fewer, because every connected component (isolated cluster of people linked by transfers) must sum to 0 and needs at least size - 1 edges!

Why do simpler shortcuts fail to find the minimum? Reimbursing pairwise-netted IOUs can take O(n^2) transfers, and greedy heuristics — even "largest debtor pays largest creditor" — can shatter clean zero-sum subsets (for instance, on {-4, +3, +2, -3, +2}, matching -4 with +3 breaks {+3, -3} and {-4, +2, +2}, taking 4 transfers instead of 3). Meanwhile, brute-forcing all (n - 1)! pairings explodes factorially, whereas bitmask dynamic programming (representing each subset of n participants as an n-bit integer and building answers from smaller subsets to larger ones) finds the exact maximum G in O(n * 2^n) time.

Here is how both methods run on Example 1 ({"Maya": 35, "Leo": 15, "Nora": -15, "Owen": -35}, with n = 4 non-zero participants):

1. Fast sweep (settle):
   Debtors: [Nora: 15, Owen: 35]    Creditors: [Maya: 35, Leo: 15]
   - Nora pays Maya 15  (Nora cleared; Maya still owed 20)
   - Owen pays Maya 20  (Maya cleared; Owen still owes 15)
   - Owen pays Leo 15   (Owen and Leo both cleared)
   -> 3 transfers: [Nora -> Maya: 15], [Owen -> Maya: 20], [Owen -> Leo: 15]

2. Optimal partition (settle_optimally):
   Split into G = 2 zero-sum subsets: {Leo: +15, Nora: -15} and {Maya: +35, Owen: -35}
   - Inside {Leo, Nora}:  Nora pays Leo 15   (2 - 1 = 1 transfer)
   - Inside {Maya, Owen}: Owen pays Maya 35  (2 - 1 = 1 transfer)
   -> n - G = 4 - 2 = 2 transfers: [Nora -> Leo: 15], [Owen -> Maya: 35]

Complexity

Let m be the total number of entries in net_positions and n (n <= m) be the number of participants with a non-zero balance.

  • settle time: O(m + n log n). We scan m entries once in O(m) to drop zeros, run the two-pointer sweep where every step clears at least one debtor or creditor in at most n - 1 iterations (O(n)), and sort at most n - 1 output triples in O(n log n).
  • settle space: O(n). We store only the debtor/creditor lists and at most n - 1 output transfers.
  • settle_optimally time: O(m + n * 2^n). Precomputing subset_sum across all 2^n bitmasks takes O(2^n) additions; filling best_groups checks n participant bits for each of the 2^n masks in O(n * 2^n) operations; reconstructing the ordering, cutting groups, sweeping each group, and sorting the output take O(n log n). In Python, n <= 18 finishes in a fraction of a second and n = 20 takes roughly one second.
  • settle_optimally space: O(2^n). The three arrays subset_sum, best_groups, and last_member each store 2^n integers (about 1 million ints each at n = 20).

Edge cases

  • Empty group ({}) or everyone already at 0 ({"Sam": 0, "Tara": 0, "Uma": 0}): Filtering leaves n = 0 non-zero participants, and both plans cleanly return {"transactions": [], "count": 0}.
  • Mix of zero and non-zero participants ({"Eli": -25, "Zoe": 0, "Kai": 25}): Zero-balance participants are dropped up front, since routing money through someone at 0 would only add wasted transfers.
  • Single creditor and multiple debtors ({"Aria": -12, "Ben": -18, "Chloe": 30}): No proper non-empty subset sums to 0, so G = 1 and both settle and settle_optimally require 3 - 1 = 2 transfers.
  • Zero-sum triples with no opposite pairs (e.g., {+1, +2, -3, +4, +5, -9}): Even though no +x / -x pair exists, the bitmask DP discovers {+1, +2, -3} and {+4, +5, -9} (G = 2, 6 - 2 = 4 transfers vs. 5 in a plain sweep).
  • Corrupted ledger (sum(amounts) != 0): Raises ValueError immediately instead of looping infinitely or leaving unpaid remainders.

Common mistakes

  • Using floating-point numbers (float) for currency: Binary floats suffer from rounding errors like 0.1 + 0.2 == 0.30000000000000004, which breaks exact zero-sum checks (subset_sum[mask] == 0); always represent money in integer minor units (cents).
  • Using elif when advancing debtor_ptr and creditor_ptr: When a debtor owes 15 and a creditor is owed 15, one transfer clears both to 0. Using elif leaves one pointer sitting on a 0 balance and emits bogus 0-cent transfers on the next step.
  • Mutating the caller's net_positions dictionary in place: Viewing a payout plan is a read-only preview; altering the input dictionary silently wipes out balances before anyone actually sends money.
  • Assuming "largest debtor pays largest creditor" is optimal: Greedy matching by size fails whenever splitting a large balance across two smaller ones unlocks extra zero-sum groups (as on {-4, +3, +2, -3, +2}).
  • Greedily peeling off small zero-sum triples first: Pairing off exact opposites (+x and -x) is always safe, because swapping elements shows an optimal partition can always keep {+x, -x} together. However, greedily removing a zero-sum triple can hurt: on {+1, +2, -3, +3, -1, -2}, grabbing {+1, +2, -3} leaves {+3, -1, -2} (2 groups, 4 transfers) instead of the three pairs {+1, -1}, {+2, -2}, {+3, -3} (3 groups, 3 transfers)!

Alternative approaches

  • Backtracking DFS over remaining balances: Pick the first non-zero participant i and try settling i's entire balance against each opposite-sign participant j (amounts[j] += amounts[i]), recursing with branch-and-bound pruning. While fast on tiny inputs, its worst-case branching factor grows like (n - 1)!, whereas bitmask DP guarantees O(n * 2^n) time.
  • Submask enumeration DP (O(3^n)): Compute dp[mask] = 1 + max(dp[sub] + dp[mask ^ sub]) by iterating over submasks of each zero-sum mask. It expresses the partition directly, but visiting all (mask, submask) pairs takes 3^n steps (~3.5 billion at n = 20) compared to n * 2^n (~20 million at n = 20) for our prefix-ordering DP.

Follow-up questions

  • How would you handle groups of 40 or 50 participants where exact subset-sum partitioning becomes too slow? Because testing whether G >= 2 is the NP-complete subset-sum problem (no known algorithm runs in polynomial time on every large input), use a layered pipeline. First, greedily cancel all exact opposite pairs +x and -x in O(n) time using a hash map — that reduction is mathematically lossless and often shrinks real groups dramatically. If the remaining n' non-zero participants satisfy n' <= 20, run the exact O(n' * 2^n') bitmask DP; otherwise, fall back to the O(n') two-pointer sweep (which uses at most n' - 1 transfers — guaranteed to be under 2x the theoretical optimum, since every zero-sum subset has at least 2 people so the optimum is at least n' / 2) or run a time-boxed integer linear programming (ILP) / heuristic search.
  • Suppose a participant modifies a past bill after teammates have already viewed a suggested payout plan. Which records update and which stay untouched? Modifying a bill writes a new version of its Expense and ExpenseShare rows (preserving the prior version in an audit log), recomputes derived group balances, and invalidates any cached or displayed payout preview so clients fetch a fresh schedule. What must remain untouched: already-recorded Payment rows represent real money that moved outside the service and stay immutable, the group's net balances must still sum to 0, retries carrying the same idempotency key (unique client request token) must not apply the edit twice, and optimistic concurrency control (expected_version) must reject stale concurrent edits instead of silently overwriting a teammate's update.
  • What changes algorithmically if transfers are restricted to pairs who already had a direct debt between them? Now repayments may only flow along existing directed edges of the pairwise debt graph rather than between arbitrary debtors and creditors, so the n - G formula no longer holds (a zero-sum subset might lack direct debt edges among its members). A clean safe simplification is cycle cancelling (finding a directed loop like U -> V -> W -> U where each person owes the next, and subtracting the smallest debt on the loop from every edge in the loop): each cancelled cycle deletes at least one debt edge without altering anyone's net balance or introducing strangers. Once all cycles are eliminated, paying the remaining edges is valid, though minimizing active edges under per-edge capacity limits requires a combinatorial search or mixed-integer solver.
  • How should the data model and settlement logic adapt when bills are logged in multiple currencies? Never sum raw integers across currencies; store an explicit ISO currency code on every bill and repayment and track independent net balances per (member_id, currency) pair, where each currency's balances sum to 0 in that currency's minor unit (noting that USD/EUR use 2 decimal places, JPY uses 0, and KWD uses 3). By default, settle each currency independently so nobody bears exchange-rate drift. If the group opts into single-currency settlement, lock and persist an explicit exchange-rate snapshot at preview/confirmation time, convert balances into the target currency's integer minor units, and assign any 1-unit rounding remainder deterministically so converted balances still sum to 0.

Follow-up questions

Similar questions

More Atlys interview questions

All 2 Atlys questions →