KatInterview

Group Expense Balancer: Greedy vs Optimal Settlement

Data Structure DesignAuto-graded · 26 test cases
MediumAuto-gradedData Structure Designgreedymemoizationsimulation

Last updated

Tests ability to implement both a greedy two-pointer debt-clearing algorithm and an exact minimum-transaction settlement using memoized recursion.

Group Expense Balancer: Greedy vs Optimal Settlement

A group of people track shared expenses. After all costs are recorded and split, each person ends up with a net position: a positive value means the group owes them money, a negative value means they owe the group money.

Your job is to turn a map of these net positions into two settlement plans that clear every balance to zero.

Input

A dictionary net_positions mapping each person's name (str) to their net balance (int). Positive means owed to them; negative means they owe others. You may assume the values sum to zero. Zero-balance entries should be ignored.

Output

Return a single dictionary with two keys:

{
  "settle": {
    "transactions": [...],
    "count": <int>
  },
  "settle_optimally": {
    "transactions": [...],
    "count": <int>
  }
}

Each entry in transactions is a three-element list [payer, payee, amount] meaning payer sends amount to payee.


settle — Greedy Plan

Use a two-pointer greedy approach:

  1. Separate people into debtors (negative balance) and creditors (positive balance).
  2. Sort both groups by name so the output is deterministic.
  3. At each step, match the first debtor with the first creditor. The payment amount is min(|debtor's balance|, creditor's balance). Advance whichever pointer is now exhausted (or both if they cancel exactly).
  4. Repeat until all balances are zero.

This produces at most n − 1 transactions for n people. It does not guarantee the minimum.


settle_optimally — Minimum-Transaction Plan

Find the settlement plan that uses the fewest possible transactions.

Use memoized recursion over the tuple of current balances:

  1. Find the first person with a negative balance.
  2. Try pairing them with every person who has a positive balance. Transfer min(|negative|, positive) between them to zero out at least one side.
  3. Recurse on the resulting state. Memoize by the full balance tuple.
  4. Among all complete plans, keep the one with the fewest transactions. Break ties lexicographically (compare the transaction tuples directly).

The names are fixed in sorted order so the state tuple maps back to names consistently.


Constraints

  • 1 ≤ len(net_positions) ≤ 8
  • All values are integers; sum(net_positions.values()) == 0
  • Names are non-empty strings containing only uppercase letters
  • Amounts fit in a 32-bit signed integer
  • If all balances are zero, both plans return empty transaction lists

Examples

Example 1

Input: settlement_plans({'A': 20, 'B': 10, 'C': -10, 'D': -20})

Output: {'settle': {'transactions': [['C', 'A', 10], ['D', 'A', 10], ['D', 'B', 10]], 'count': 3}, 'settle_optimally': {'transactions': [['C', 'B', 10], ['D', 'A', 20]], 'count': 2}}

Example 2

Input: settlement_plans({'A': 5, 'B': -5})

Output: {'settle': {'transactions': [['B', 'A', 5]], 'count': 1}, 'settle_optimally': {'transactions': [['B', 'A', 5]], 'count': 1}}

Example 3

Input: settlement_plans({'A': -10, 'B': -10, 'C': 20})

Output: {'settle': {'transactions': [['A', 'C', 10], ['B', 'C', 10]], 'count': 2}, 'settle_optimally': {'transactions': [['A', 'C', 10], ['B', 'C', 10]], 'count': 2}}

Example 4

Input: settlement_plans({'A': 0, 'B': 0})

Output: {'settle': {'transactions': [], 'count': 0}, 'settle_optimally': {'transactions': [], 'count': 0}}

Hints

Hint 1

Split the net_positions dict into two lists — one for people who owe money (negative balance) and one for people who are owed money (positive balance). Sorting both lists by name keeps the greedy output deterministic.

Hint 2

For the optimal solution, represent the current state as a tuple of balances (in a fixed name order). Memoize on that tuple so you never recompute the same partial state twice.

Hint 3

The minimum number of transactions equals the number of people whose balance is non-zero after netting, minus the maximum number of balances you can cancel in a single chain. A simpler bound: it can never be less than max(number of debtors, number of creditors).