Group Expense Ledger and Minimum-Transfer Settlement

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

A group of friends sharing a weekend cabin trip needs a backend service to record shared bills—such as groceries, firewood, and kayak rentals—and figure out who should pay whom at the end of the trip. Whenever someone pays a bill, they log the total charge and how that charge is divided among participants. From those records, the service computes a single signed net balance (in integer cents) for each participant within the group:

  • A positive value means the participant covered more than their share and is owed that many cents back.
  • A negative value means the participant owes that many cents toward the group's bills.
  • A zero value means the participant is already settled up.

Because every cent paid by someone is assigned to someone's share, the net balances across a group always sum to 0.

This problem has two parts:

  1. System & API Design: Outline the core domain models, public service endpoints, and data-integrity guarantees needed for a production shared-expense service:
    • Support independent expense groups (so two people who belong to multiple trips keep separate per-group balances), flexible split rules (equal division, exact cent amounts, percentage splits, and weighted share ratios), and single-currency integer-cent accounting with deterministic penny allocation when a bill does not divide evenly.
    • Guarantee that network retries never lose or duplicate bills or payments, concurrent writes cannot corrupt balances, and generating a suggested settlement preview never mutates stored balances or creates fake payment records (kept strictly separate from an append-only log of actual completed transfers).
  2. Settlement Algorithms: Implement two pure functions (without mutating the input dictionary):
    • settle(balances: Dict[str, int]) -> List[List[object]]: Partition participants with negative balances (debtors) and positive balances (creditors) in the iteration order of balances, skipping anyone with a 0 balance, and greedily pair the current debtor with the current creditor by transferring min(remaining_debt, remaining_credit) until every balance reaches 0. Return each transfer as [payer, payee, amount]. (The automated judge evaluates settle.)
    • settle_optimally(balances: Dict[str, int]) -> List[List[object]]: Return a valid list of [payer, payee, amount] transfers that brings every participant's balance to 0 using the smallest possible number of transfers.
def settle(balances: Dict[str, int]) -> List[List[object]]:
    pass

Examples

Example 1

Input:  balances = {"Leo": 900, "Nora": 300, "Omar": -300, "Zoe": -900}
Output (settle):           [["Omar", "Leo", 300], ["Zoe", "Leo", 600], ["Zoe", "Nora", 300]]
Output (settle_optimally): [["Zoe", "Leo", 900], ["Omar", "Nora", 300]] (any 2-transfer valid plan)

Walk-through: Suppose Leo paid 1200 cents split four ways (300 each), Nora paid 900 cents split among Nora, Omar, and Zoe (300 each), and Omar paid 600 cents split between Omar and Zoe (300 each). Their net balances are Leo: +900, Nora: +300, Omar: -300, and Zoe: -900. - In settle, debtors in input order are Omar (300) then Zoe (900), and creditors are Leo (900) then Nora (300). Omar pays Leo 300 (clearing Omar and leaving Leo owed 600), Zoe pays Leo 600 (clearing Leo and leaving Zoe owing 300), and finally Zoe pays Nora 300, taking 3 transfers total. - In settle_optimally, Zoe pays Leo 900 directly and Omar pays Nora 300 directly, clearing all four balances in just 2 transfers.

Example 2

Input:  balances = {"Dana": -400, "Eli": 0, "Finn": -650, "Gwen": 1050}
Output (settle): [["Dana", "Gwen", 400], ["Finn", "Gwen", 650]]

Walk-through: Eli already has a 0 balance and is skipped. Dana pays Gwen 400 cents (reducing Gwen's remaining credit to 650), and then Finn pays Gwen 650 cents, leaving everyone at 0. Here 2 transfers is also the theoretical minimum.

Constraints

  • 0 <= len(balances) <= 12 for settle_optimally (settle runs in linear time for any group size).
  • Every key in balances is a unique non-empty participant identifier (str), and every value is a signed integer in cents (int).
  • sum(balances.values()) == 0.
  • Every returned transfer [payer, payee, amount] must reference distinct participants in balances with a strictly positive integer amount > 0, and neither function may mutate balances.

Step-by-step walkthrough

  1. Understand the net-balance model and the two settlement goals

    When friends share bills on a cabin trip, tracking a separate IOU between every pair of people quickly turns into a tangled web of payments. Instead, we can imagine a central group pot:

    • A positive net balance (+900) means the pot owes that participant 900 cents (they paid more than their share). We call them a creditor.
    • A negative net balance (-300) means that participant owes the pot 300 cents (others covered their share). We call them a debtor.
    • Because every cent paid into a shared bill is assigned to someone in the group, all net balances always add up to 0.
    Cabin trip bills (in cents):
      Leo pays 1200 split 4 ways (300 each)   -> Leo +900, Nora -300, Omar -300, Zoe -300
      Nora pays 900 split 3 ways (300 each)   -> Nora +600, Omar -300, Zoe -300
      Omar pays 600 split 2 ways (300 each)   -> Omar +300, Zoe -300
      -----------------------------------------------------------------------------------
      Running net balances:                   Leo: +900, Nora: +300, Omar: -300, Zoe: -900
    

    Both settlement functions take balances: Dict[str, int] (in integer cents, so floating-point rounding never corrupts money) and return a list of [payer, payee, amount] transfers without mutating balances:

    • settle(balances) pairs debtors and creditors greedily in input dictionary order (the automated judge checks settle).
    • settle_optimally(balances) finds a valid plan using the fewest possible transfers (2 transfers on Example 1 instead of 3).
  2. Part 1: Design the entities, API, and money-safety rules

    Before writing the algorithms, Part 1 asks how the surrounding expense-tracker service keeps balances accurate when real people log bills and send money concurrently.

    The cleanest architecture separates append-only facts (logged bills and real-money transfers that actually happened) from derived views (current balances and preview settlement plans):

    +--------------------+       +-----------------------+
    | Expense            |       | ExpenseShare          |
    | - id               |1     *| - expense_id          |
    | - group_id         |------>| - member_id           |
    | - paid_by          |       | - share_cents         |
    | - amount_cents     |       +-----------------------+
    | - idempotency_key  |
    +--------------------+
              \
               \   derived net balance(m) =
                +--> (expenses m paid - shares m owed) + (transfers m sent - transfers m received)
               /
    +--------------------+
    | Transfer           |   <-- append-only log of REAL payments actually made
    | - id, group_id     |
    | - payer, payee     |
    | - amount_cents     |
    | - idempotency_key  |
    +--------------------+
    

    Public API sketch:

    • add_expense(group_id, paid_by, amount_cents, split_spec, idempotency_key) -> expense_id (supports EQUAL, EXACT, PERCENT, and weighted SHARES splits, scoped per group).
    • get_balances(group_id) -> Dict[member_id, int] (derived read-only snapshot in cents).
    • plan_settlement(group_id, optimal: bool) -> List[[payer, payee, cents]] (pure preview — writes nothing to the database).
    • record_transfer(group_id, payer, payee, amount_cents, idempotency_key) -> transfer_id (records an actual payment).
    • get_history(group_id, member_id) -> List[Expense | Transfer] (chronological audit trail).

    Four non-functional guarantees protect users' money:

    1. No lost or double-counted writes: Clients attach a unique idempotency_key (a request ID generated once per button tap) so network retries return the existing record instead of charging twice.
    2. Concurrency safety: Balances are derived from the append-only logs. If cached in a GroupBalance row, update them inside the same database transaction using atomic SQL increments (SET balance_cents = balance_cents + delta), never an application-level read-modify-write that could lose a concurrent update.
    3. Deterministic cent rounding: Resolve percentages or uneven splits into integer cents at write time (for example, 1000 cents split 3 ways becomes 334, 333, 333, assigning leftover pennies in sorted member_id order) so sum(share_cents) == amount_cents always holds.
    4. Preview vs. execution separation: Calling settle or settle_optimally never mutates stored balances; only record_transfer records real money movement.
  3. Part 2a: Greedy two-pointer settlement (`settle`)

    To settle balances simply and predictably, split participants into two lists while preserving input order:

    • debtors: [name, -balance] for everyone with balance < 0 (flipping the sign so debt_left is positive).
    • creditors: [name, balance] for everyone with balance > 0.
    • Participants with balance == 0 (such as "Eli" in Example 2) are skipped completely.

    Now maintain two pointers, debtor_idx and creditor_idx. At each step, the current debtor pays the current creditor min(debt_left, credit_left):

    • Neither person ever overshoots 0, because we cap the transfer at the smaller of the two remaining amounts.
    • At least one of the two remaining amounts drops to 0, so at least one pointer moves forward on every iteration.
    • Because total debt equals total credit, both lists finish at the exact same moment!

    One critical detail: use two separate if checks (not elif) when advancing debtor_idx and creditor_idx. When debt_left == credit_left, a single transfer settles both people at once — if only one pointer moved, the next loop iteration would emit a bogus 0-cent payment!

    def settle(balances: Dict[str, int]) -> List[List[object]]:
        """Return a valid list of [payer, payee, amount] transfers using greedy pairing."""
        # debtors: list of [member_name, cents_still_owed_by_member], e.g. [["Omar", 300], ["Zoe", 900]]
        debtors: List[List[Any]] = []
        # creditors: list of [member_name, cents_still_owed_to_member], e.g. [["Leo", 900], ["Nora", 300]]
        creditors: List[List[Any]] = []
    
        # Phase 1: Partition non-zero balances in input order without mutating the caller's dict.
        for name, balance in balances.items():
            if balance < 0:
                # Flip the negative balance into a positive amount the debtor needs to pay out.
                debtors.append([name, -balance])
            elif balance > 0:
                creditors.append([name, balance])
    
        # Phase 2: Greedily match the current debtor with the current creditor.
        payments: List[List[object]] = []
        debtor_idx = 0
        creditor_idx = 0
        while debtor_idx < len(debtors) and creditor_idx < len(creditors):
            debtor_name, debt_left = debtors[debtor_idx]
            creditor_name, credit_left = creditors[creditor_idx]
    
            # Transfer as much as possible without making either side overshoot zero.
            payment_cents = min(debt_left, credit_left)
            payments.append([debtor_name, creditor_name, payment_cents])
    
            debtors[debtor_idx][1] -= payment_cents
            creditors[creditor_idx][1] -= payment_cents
    
            # Use two separate `if` checks (not `elif`): when debt_left == credit_left,
            # both sides reach 0 on the same transfer and both pointers must advance.
            if debtors[debtor_idx][1] == 0:
                debtor_idx += 1
            if creditors[creditor_idx][1] == 0:
                creditor_idx += 1
    
        return payments
    
  4. Trace `settle` on Example 1

    On {'Leo': 900, 'Nora': 300, 'Omar': -300, 'Zoe': -900}, input order gives debtors = [['Omar', 300], ['Zoe', 900]] and creditors = [['Leo', 900], ['Nora', 300]]:

    Step  Current debtor  Current creditor  Transfer               Remaining after step
    ----  --------------  ----------------  ---------------------  ----------------------------------
    1     Omar (300)      Leo (900)         [Omar, Leo, 300]       Omar: 0 (advance), Leo: 600
    2     Zoe (900)       Leo (600)         [Zoe, Leo, 600]        Zoe: 300, Leo: 0 (advance)
    3     Zoe (300)       Nora (300)        [Zoe, Nora, 300]       Zoe: 0 (advance), Nora: 0 (advance)
    

    settle returns [['Omar', 'Leo', 300], ['Zoe', 'Leo', 600], ['Zoe', 'Nora', 300]] — valid and O(n) fast, though it took 3 transfers when 2 would suffice.

  5. Why greedy uses extra transfers: zero-sum groups

    Why can Example 1 be settled in 2 transfers instead of 3? Look at the two settlement graphs side by side:

    Greedy pairing (1 connected group of 4 people -> 4 - 1 = 3 transfers):
      Omar (-300) --300--> Leo (+900) <--600-- Zoe (-900) --300--> Nora (+300)
    
    Optimal pairing (2 independent zero-sum groups -> 4 - 2 = 2 transfers):
      Group 1: Zoe (-900) --900--> Leo (+900)       (sum = -900 + 900 = 0, 1 transfer)
      Group 2: Omar (-300) --300--> Nora (+300)     (sum = -300 + 300 = 0, 1 transfer)
    

    Suppose there are n people with non-zero balances. Think of people as nodes and transfers as edges:

    1. Money never leaves a connected component of transfers, so the balances inside every connected component must sum to 0.
    2. Connecting m people into one component takes at least m - 1 transfers (a tree on m nodes has m - 1 edges).

    If the n non-zero balances can be split into at most G disjoint zero-sum groups of sizes m_1, m_2, ..., m_G, then the minimum number of transfers is:

    (m_1 - 1) + (m_2 - 1) + ... + (m_G - 1) = n - G
    

    Finding whether any subset sums to 0 is the classic subset-sum problem (NP-hard in general), which is why no simple greedy sorting rule always finds the optimum. Fortunately, typical shared-expense groups have small n, so backtracking with pruning solves it cleanly.

  6. Part 2b: Backtracking with branch-and-bound (`settle_optimally`)

    To search all relevant plans without wasting work, settle_optimally processes the non-zero amounts list from left to right:

    1. Advance start past any entries that are already 0. If start == len(amounts), every balance is settled — save current_plan if it beats best_plan.
    2. Prune early (branch and bound): We initialize best_plan = settle(balances). Since amounts[start] is non-zero, at least 1 more transfer is required. Whenever len(current_plan) + 1 >= len(best_plan), this branch cannot possibly produce fewer transfers than best_plan, so return immediately!
    3. Try every opposite-sign partner other > start: Shift start's entire balance onto other in a single transfer (amounts[other] += start_amount, amounts[start] = 0), recurse on start + 1, and undo the change afterward.

    Why is shifting start's entire balance onto a single opposite-sign partner guaranteed to include an optimal plan? In any optimal zero-sum group containing start, all other members of that group sit at indices > start, and because the group sums to 0, at least one member other in start's group has the opposite sign. Transferring start's balance onto that other uses 1 transfer, removes start, and leaves the rest of start's group still summing to 0 — staying right on an optimal n - G trajectory!

    Example 1 search trace on amounts = [Leo +900, Nora +300, Omar -300, Zoe -900], initial best = 3:
      start=0 (Leo +900):
        -> pair with Omar (-300): Omar pays Leo 900 -> amounts = [0, +300, +600, -900] (1 transfer)
           start=1 (Nora +300):
             -> pair with Zoe (-900): len(current_plan)=1, after Nora<->Zoe len=2, still unsettled -> pruned at 2+1 >= 3!
        -> pair with Zoe (-900): Zoe pays Leo 900   -> amounts = [0, +300, -300, 0]    (1 transfer)
           start=1 (Nora +300):
             -> pair with Omar (-300): Omar pays Nora 300 -> amounts = [0, 0, 0, 0] (2 transfers < 3 -> new best!)
    
  7. Complete solution

    Putting both settle (called by the judge) and settle_optimally together:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def settle(balances: Dict[str, int]) -> List[List[object]]:
        """Return a valid list of [payer, payee, amount] transfers using greedy pairing."""
        # debtors: list of [member_name, cents_still_owed_by_member], e.g. [["Omar", 300], ["Zoe", 900]]
        debtors: List[List[Any]] = []
        # creditors: list of [member_name, cents_still_owed_to_member], e.g. [["Leo", 900], ["Nora", 300]]
        creditors: List[List[Any]] = []
    
        # Phase 1: Partition non-zero balances in input order without mutating the caller's dict.
        for name, balance in balances.items():
            if balance < 0:
                # Flip the negative balance into a positive amount the debtor needs to pay out.
                debtors.append([name, -balance])
            elif balance > 0:
                creditors.append([name, balance])
    
        # Phase 2: Greedily match the current debtor with the current creditor.
        payments: List[List[object]] = []
        debtor_idx = 0
        creditor_idx = 0
        while debtor_idx < len(debtors) and creditor_idx < len(creditors):
            debtor_name, debt_left = debtors[debtor_idx]
            creditor_name, credit_left = creditors[creditor_idx]
    
            # Transfer as much as possible without making either side overshoot zero.
            payment_cents = min(debt_left, credit_left)
            payments.append([debtor_name, creditor_name, payment_cents])
    
            debtors[debtor_idx][1] -= payment_cents
            creditors[creditor_idx][1] -= payment_cents
    
            # Use two separate `if` checks (not `elif`): when debt_left == credit_left,
            # both sides reach 0 on the same transfer and both pointers must advance.
            if debtors[debtor_idx][1] == 0:
                debtor_idx += 1
            if creditors[creditor_idx][1] == 0:
                creditor_idx += 1
    
        return payments
    
    
    def settle_optimally(balances: Dict[str, int]) -> List[List[object]]:
        """Return a valid settlement plan with the minimum possible number of transfers."""
        # Phase 1: Extract only members with non-zero balances into parallel working lists.
        # names[i] has remaining signed balance amounts[i] (negative = owes, positive = owed).
        names: List[str] = []
        amounts: List[int] = []
        for name, balance in balances.items():
            if balance != 0:
                names.append(name)
                amounts.append(balance)
    
        # Seed best_plan with the greedy solution so branch-and-bound has a tight upper bound.
        best_plan: List[List[object]] = settle(balances)
        # current_plan: stack of [payer, payee, cents] transfers chosen along the active search branch.
        current_plan: List[List[object]] = []
    
        # Phase 2: Backtrack over who absorbs the entire balance of the first unsettled member.
        def search(start: int) -> None:
            nonlocal best_plan
    
            # Skip members whose balance was already cancelled out by an earlier transfer.
            while start < len(amounts) and amounts[start] == 0:
                start += 1
    
            # Base case: everyone is at 0, so current_plan is a complete settlement.
            if start == len(amounts):
                if len(current_plan) < len(best_plan):
                    best_plan = list(current_plan)
                return
    
            # Pruning: `start` still has a non-zero balance, so we need at least 1 more transfer.
            # If len(current_plan) + 1 cannot strictly beat best_plan, abandon this branch early.
            if len(current_plan) + 1 >= len(best_plan):
                return
    
            start_amount = amounts[start]
            for other in range(start + 1, len(amounts)):
                other_amount = amounts[other]
    
                # Only pair opposite signs (a debtor with a creditor); same-sign or zero transfers
                # never bring two balances closer to cancelling out.
                has_opposite_sign = (start_amount < 0 and other_amount > 0) or (
                    start_amount > 0 and other_amount < 0
                )
                if not has_opposite_sign:
                    continue
    
                # Clear `start` in a single transfer by shifting its whole balance onto `other`.
                if start_amount < 0:
                    current_plan.append([names[start], names[other], -start_amount])
                else:
                    current_plan.append([names[other], names[start], start_amount])
    
                amounts[other] += start_amount
                amounts[start] = 0
    
                search(start + 1)
    
                # Undo the transfer so the next loop iteration starts from a clean state.
                amounts[start] = start_amount
                amounts[other] = other_amount
                current_plan.pop()
    
        search(0)
        return best_plan
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine four friends finishing a weekend cabin trip with a stack of grocery, firewood, and kayak-rental receipts. Instead of making everyone reimburse everyone else receipt by receipt, imagine putting a hypothetical group pot in the middle of the table: each participant calculates a single net balance (one signed integer equal to total cents they paid for the group minus total cents of their own shares). Anyone with a negative balance owes money into the pot (a debtor), and anyone with a positive balance is owed money out of the pot (a creditor).

Why does a naive approach fall short? Keeping a pairwise matrix of who owes whom across n people can produce up to n * (n - 1) / 2 separate payments even when debts cancel in a circle (A owes B, B owes C, C owes A). Collapsing to net balances eliminates circular debts, and a greedy algorithm (making the locally simplest choice at each step — pairing the front debtor with the front creditor) settles everyone in at most n - 1 payments. However, greedy pairing still misses hidden exact matches that split the group into independent zero-sum subsets (smaller subgroups whose balances add up to zero on their own), whereas trying every possible transfer graph blindly without pruning explodes combinatorially.

Walk through Example 1 ({'Leo': 900, 'Nora': 300, 'Omar': -300, 'Zoe': -900}):

1. Greedy `settle` (pairs debtors [Omar 300, Zoe 900] with creditors [Leo 900, Nora 300] in order):
   - Omar pays Leo 300   -> Omar is cleared (0), Leo still needs 600
   - Zoe pays Leo 600    -> Leo is cleared (0), Zoe still owes 300
   - Zoe pays Nora 300   -> Zoe and Nora both hit 0  --> 3 transfers total

2. Optimal `settle_optimally` (backtracking with branch-and-bound pruning):
   - Branch 1: Omar (-300) absorbs Leo (+900) -> pruned once depth + 1 hits 3
   - Branch 2: Zoe (-900) pays Leo (+900)  -> both hit 0!
               Omar (-300) pays Nora (+300) -> both hit 0!  --> 2 transfers total

In settle_optimally, we use backtracking (recursively trying candidate choices and undoing them on return) combined with branch and bound (tracking the best complete answer seen so far — initialized to the greedy settle plan — and abandoning any partial search path as soon as it cannot beat that bound).

Complexity

Let m be the total number of participants in balances, and let n (n <= m) be the number of participants with non-zero balances (D debtors and C creditors, so n = D + C).

  • settle time: O(m). We scan all m dictionary entries once to build debtors and creditors, and each iteration of the while loop zeroes out at least one debtor or creditor and advances its pointer, so the loop runs at most D + C - 1 < m times with O(1) work per step.
  • settle space: O(m). The debtors, creditors, and output payments lists each store at most m entries.
  • settle_optimally time: O((n - 1)! * n) worst case (exponential in n). Finding the maximum number of zero-sum subsets is NP-hard (at least as hard as the subset-sum problem, which asks whether any subset of numbers adds up to zero, so no polynomial-time algorithm is known). At unsettled index s, the loop tries at most n - 1 - s later opposite-sign partners, creating at most (n - 1)! search leaves; branch-and-bound cuts off many branches early, easily handling groups of ~12 participants.
  • settle_optimally space: O(m). Filtering non-zero balances takes O(n), the recursion call stack goes at most n levels deep, and current_plan plus best_plan each hold at most n - 1 transfers.

Edge cases

  • Empty input {} or all zero balances {'Leo': 0, 'Nora': 0}: Both debtors and creditors are empty, so both functions immediately return [].
  • Participants with 0 balance mixed with active participants (such as 'Eli': 0 in Example 2): Skipped during Phase 1, so someone who is already square never sends or receives a transfer.
  • Equal debtor and creditor mid-scan ({'A': 10, 'B': -10, 'C': 5, 'D': -5}): Both pointers advance on the same iteration, avoiding a 0-cent follow-up transfer.
  • Single debtor owing multiple creditors (or vice versa): settle emits one transfer per creditor, which is also optimal because no smaller non-empty subset can sum to 0.
  • Pass-through transfers in settle_optimally: Because settle_optimally shifts start's entire balance onto one opposite-sign partner, an intermediate participant may temporarily over-receive and forward the excess (for example, on {A: -4, B: -4, C: 1, D: 4, E: 3}, A pays C 4 and C pays E 3). If a product requires strictly debtor-to-creditor payments without pass-throughs, take each connected component (isolated subgroup of people linked by transfers) from settle_optimally and run settle inside each component — the transfer count stays minimal!

Common mistakes

  • Representing money with floating-point numbers (float): Binary floats cannot represent 0.10 exactly (0.1 + 0.2 != 0.3), causing balances to fail == 0 checks by 1e-16; always store integer minor units (cents).
  • Mutating the caller's balances dictionary: Previewing a settlement plan must be side-effect-free; modifying balances in place corrupts the caller's state before any real payment occurs.
  • Using elif instead of two ifs when advancing debtor_idx and creditor_idx: When debt_left == credit_left, elif leaves one zeroed-out participant at the front and produces a 0-cent transfer on the next iteration.
  • Sorting debtors and creditors inside settle: Sorting changes the payment pairs away from the input-order baseline expected by sample tests, and largest-first greedy still fails to minimize transfers (for instance, on {4, -6, -8, -8, 3, 9, 6} largest-first uses 6 transfers, while {6, -6} plus {4, 3, 9, -8, -8} needs only 5).
  • Forgetting to restore amounts and current_plan after recursion: In backtracking, mutating shared arrays without undoing amounts[start], amounts[other], and current_plan.pop() leaks state into sibling branches.

Alternative approaches

  • Bitmask dynamic programming (O(n * 2^n) time, O(2^n) space): A bitmask represents a subset of the n people as an n-bit integer where bit i is 1 if person i is included. Precompute subset_sum[mask] for every mask from 1 to 2^n - 1, then compute max_groups[mask] — the largest number of zero-sum groups mask can be partitioned into — by taking max(max_groups[mask ^ (1 << i)]) over set bits i, plus 1 whenever subset_sum[mask] == 0. For n = 16..20, O(n * 2^n) is much faster and more predictable than O((n - 1)!) factorial branching.
def min_transfer_count_bitmask(balances: Dict[str, int]) -> int:
    values = [v for v in balances.values() if v != 0]
    n = len(values)
    if n == 0:
        return 0
    subset_sum = [0] * (1 << n)
    max_groups = [0] * (1 << n)
    for mask in range(1, 1 << n):
        lowest_bit = mask & -mask
        idx = lowest_bit.bit_length() - 1
        subset_sum[mask] = subset_sum[mask ^ lowest_bit] + values[idx]
        best_prev = 0
        for i in range(n):
            if mask & (1 << i):
                best_prev = max(best_prev, max_groups[mask ^ (1 << i)])
        max_groups[mask] = best_prev + (1 if subset_sum[mask] == 0 else 0)
    return n - max_groups[(1 << n) - 1]

Follow-up questions

  • How would your schema and settlement logic adapt if participants log bills in several different currencies that cannot be added directly? Key every ledger balance by (group_id, member_id, currency) rather than (group_id, member_id), and store integer minor units appropriate to each currency (for example, cents for USD vs. whole yen for JPY). By default, run settle or settle_optimally independently per currency slice — since each bill was recorded in one currency, every currency slice sums to zero on its own. If the group opts to settle everything in a single home currency, convert each currency's net balances at a locked-in exchange rate and write an explicit FX-conversion entry into the append-only log (a history table where rows are only inserted, never overwritten) so rounding pennies and exchange rates stay auditable.
  • When a group grows to around 30 participants, exact exponential search becomes too slow—how would you keep near-optimal settlement fast at that scale? At n = 30, both factorial backtracking and 2^30 bitmask DP exceed interactive latency budgets, so combine fast exact reductions with a bounded heuristic. First, greedily cancel all exact opposite pairs (+x and -x) in O(n) using a hash map — this never hurts optimality — and optionally cancel exact zero-sum triples (a + b + c == 0). On the remaining k non-zero balances, start with greedy pairing (which uses at most k - 1 transfers vs. a lower bound of ceil(k / 2), guaranteeing at worst a 2x approximation) and run branch-and-bound under a strict time budget (say 50 ms) to tighten best_plan before returning.
  • How would you model an auditable timeline of completed peer-to-peer payments without conflating it with current unpaid balances? Record executed payments in an immutable Transfer(id, group_id, payer, payee, amount_cents, created_at, idempotency_key) table indexed on (group_id, payer, created_at) and (group_id, payee, created_at), where an idempotency key is a unique client-generated token preventing duplicate rows on network retries. get_history reads directly from Transfer (and Expense), whereas get_balances combines logged expenses and completed transfers to derive what remains unpaid. Because settle and settle_optimally are read-only preview functions, suggested transfers never appear in payment history until money actually moves.
  • Suppose a participant has only completed half of a recommended settlement plan when someone logs a new shared bill—how should the system handle the remaining recommendations? Attach a monotonically increasing ledger_version to each group's state and return that version with every settlement preview. Any transfers already completed before the new bill are recorded normally via record_transfer and remain completely valid, because each completed transfer simply shifts net balances closer to zero while preserving the zero-sum invariant. Once the new bill increments ledger_version, clients mark any unexecuted steps from the older preview as stale and request a fresh settlement plan computed from the updated net balances.

Follow-up questions

Similar questions

More Atlys interview questions

All 2 Atlys questions →