Minimize Payment Transfers to Balance Group Accounts
Dynamic ProgrammingAuto-graded · 24 test casesLast updated
Tests backtracking with memoization to find the smallest number of payments needed to settle net balances across multiple participants.
A group of people have been tracking their shared expenses. You receive a log of transactions where each entry transactions[i] = [payer, recipient, amount] means person payer paid amount dollars on behalf of person recipient.
Each person has a net balance: the total they paid for others minus the total others paid for them. To balance everyone's accounts, participants must make direct payments to each other until every person's net balance reaches zero.
Your task is to determine the minimum number of direct payments required to settle all accounts.
Constraints
1 <= len(transactions) <= 1000- Each transaction is
[payer, recipient, amount]wherepayer != recipient 0 <= payer, recipient <= 1001 <= amount <= 1000- The number of people with non-zero net balances will not exceed
12
Examples
Example 1
Input: min_payments_to_settle([[0, 1, 10], [2, 0, 5]])
Output: 2
Example 2
Input: min_payments_to_settle([[0, 1, 10], [1, 0, 1], [1, 2, 5], [2, 0, 5]])
Output: 1
Hints
Hint 1
The original transaction history doesn't matter—only each person's net balance (what they're owed or what they owe) is relevant.
Hint 2
A group of k people whose net balances sum to zero can always be settled in k-1 payments, but finding the true minimum requires checking if the group can be split into independent subgroups.
Hint 3
Use backtracking: pick one person with a non-zero balance, try settling their entire debt with each person of opposite sign, then recursively solve the remaining balances. Memoize on the sorted balance tuple to avoid recomputing identical states.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that the original transaction log is irrelevant—only each person's net balance matters. Calculate how much each person is owed (positive balance) or owes (negative balance), then solve the optimization problem on these net values.
Algorithm Steps
-
Compute net balances. For each transaction where person A pays for person B, subtract from A's balance and add to B's balance. The result is a list showing who needs to receive money (positive) and who needs to pay (negative).
-
Filter and canonicalize. Remove anyone with a zero balance. Sort the remaining balances to create a canonical state representation for memoization.
-
Backtracking search. Pick the first unsettled person. Try settling their entire balance by making one payment to each person with opposite sign (creditor pays debtor, or vice versa). This zeroes out one person. Recursively solve the remaining state and track the minimum.
-
Optimizations:
- Memoization: Cache results based on the sorted tuple of balances, since different orderings of the same multiset yield identical subproblems.
- Skip duplicates: If two people have identical balances, settling with either produces the same resulting state. Only try one.
- Early termination: If you find an exact match (two balances that sum to zero), that pairing zeroes both people in one payment and is always optimal for that branch.
Why It Works
Any group of k people whose balances sum to zero can be settled in at most k - 1 payments. The minimum occurs when the group can be partitioned into independent zero-sum subgroups. By exhaustively trying all valid pairings via backtracking and memoizing on canonical states, we explore the space of possible partitions and find the one requiring the fewest payments.
Complexity
Let n be the number of people with non-zero balances (n ≤ 12).
- Time:
O(n! · n log n)in the worst case without heavy pruning, but memoization, duplicate skipping, and exact-match pruning collapse most branches. Forn ≤ 12this runs quickly in practice. - Space:
O(n)recursion depth plus the memoization table storing visited states.
Building the initial balances takes O(T) where T is the number of transactions.
from typing import List
from functools import lru_cache
def min_payments_to_settle(transactions: List[List[int]]) -> int:
# Calculate net balance for each person
net = [0] * 101
for payer, recipient, amount in transactions:
net[payer] -= amount
net[recipient] += amount
# Extract only non-zero balances and sort for canonical representation
balances = tuple(sorted(b for b in net if b != 0))
@lru_cache(None)
def backtrack(state: tuple) -> int:
state = list(state)
# Find first unsettled person
idx = 0
while idx < len(state) and state[idx] == 0:
idx += 1
# All settled
if idx == len(state):
return 0
min_payments = len(state) # Upper bound
visited = set()
for j in range(idx + 1, len(state)):
# Skip if same sign or already tried this balance value
if state[idx] * state[j] >= 0 or state[j] in visited:
continue
visited.add(state[j])
# Make payment: person idx settles entirely with person j
new_state = state[:]
new_state[j] += new_state[idx]
new_state[idx] = 0
min_payments = min(min_payments, 1 + backtrack(tuple(sorted(new_state))))
# If exact match found, this is optimal for this branch
if state[j] + state[idx] == 0:
break
return min_payments
return backtrack(balances)