Optimal Account Balancing

Hard

Topics
ArrayDynamic ProgrammingBacktrackingBit ManipulationBitmask

You are given an array of transactions where transactions[i] = [from, to, amount] means that the person with ID from gave amount dollars to the person with ID to.

Return the minimum number of transactions required to settle the debt, so that afterwards nobody owes anybody anything.

A settling transaction can be between any two people for any amount; you are not restricted to reversing the transactions that happened.

The judge names this argument grid, since it feeds every matrix problem through the same reader. It is the transactions array above, one row per transaction.

Example 1

net-5#010#1-5#2
still owes or is owed
Each cell is one person’s net position after all 2 transactions — money paid out counts negative, money received positive, and who it went to is already folded in. Settling the remaining 3 balances takes 2 payments.
Each transaction in the input is one row of [from, to, amount]; the figure shows the nets they add up to.
Input:  transactions = [[0,1,10],[2,0,5]]
Output: 2
Explanation: Person 1 ends up 10 ahead; persons 0 and 2 end up 5 behind each. Person 1 pays 5 to each of them, which is two transactions.

Example 2

net-4#04#10#2
still owes or is owedalready square
Anyone who came out square drops out of the problem entirely, which is 1 person here.
Input:  transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output: 1
Explanation: The nets cancel down to person 1 being 4 ahead and person 0 being 4 behind, so one payment settles everything.

Example 3

net-5#00#15#2
still owes or is owedalready square
Input:  transactions = [[0,1,5],[1,2,5]]
Output: 1
Explanation: Person 1 received 5 and paid 5, so person 1 is square and drops out entirely. Only 0 and 2 remain.

Constraints

  • 1 <= transactions.length <= 8
  • transactions[i].length == 3
  • 0 <= from, to < 12
  • from != to
  • 1 <= amount <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The individual transactions do not matter. If a person paid out 10 and took in 7, the only thing that survives is the net -3; who it was paid to is already accounted for in that person’s own net. So the first move collapses the whole history into one number per person.

Anyone whose net is zero disappears from the problem, which matters more than it looks — example 3 has three people but only two of them participate.

What remains is a list of positive and negative numbers that sums to zero, and the question is how few payments can zero them all out. Each payment can zero at most one person, so with k non-zero people the answer is between k/2 and k - 1, and finding the exact value means deciding which debtor to pair with which creditor.

Approach

  1. Build a balance per person: subtract the amount from the payer and add it to the recipient.
  2. Discard every zero balance. Only the non-zero ones are part of the problem.
  3. Settle the first non-zero balance. Pair it with each later balance of the opposite sign in turn: hand the whole of the first balance over, which zeroes it and leaves the partner changed.
  4. Recurse on the shortened list, counting one transaction for the pairing, and keep the cheapest total. Undo the change before trying the next partner so the branches stay independent.
  5. A list with nothing non-zero left costs zero transactions, which ends the recursion.

Walkthrough

transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]

net per person
  0: -10 +1 +5  = -4
  1: +10 -1 -5  = +4
  2:      +5 -5 =  0   -> drops out

non-zero balances: [-4, +4]

pair -4 with +4   ->  [0, 0]   one transaction, nothing left

answer 1

Complexity

  • Time — O(n!): in the worst case every debtor can be paired with every creditor, and the recursion explores those pairings. With at most 12 people and 8 transactions the tree stays small.
  • Space — O(n): the balance list plus the recursion depth, both bounded by the number of people.

Common Pitfalls

  • Keeping people whose net is zero in the list. They can never need a payment, and leaving them in both wastes branches and can make an off-by-one in the count.
  • Pairing two balances of the same sign. Handing money from one debtor to another leaves the total debt unchanged and the search never terminates usefully.
  • Treating the answer as "number of non-zero people minus one". That is only the upper bound — example 1 has three non-zero people and needs two payments, but a case where two debts cancel exactly needs fewer.
  • Forgetting to undo the change to the partner before the next iteration, which silently corrupts every later branch.

Full Solution — all languages

class Solution:
    def minTransfers(self, grid):
        net = {}
        for frm, to, amount in grid:
            net[frm] = net.get(frm, 0) - amount
            net[to] = net.get(to, 0) + amount
        bal = [v for v in net.values() if v != 0]

        def settle(i):
            while i < len(bal) and bal[i] == 0:
                i += 1
            if i == len(bal):
                return 0
            best = float('inf')
            for j in range(i + 1, len(bal)):
                if bal[i] * bal[j] < 0:
                    bal[j] += bal[i]
                    best = min(best, 1 + settle(i + 1))
                    bal[j] -= bal[i]
            return best

        answer = settle(0)
        return 0 if answer == float('inf') else answer
SensAI
Beta
Tap the mic to stop voice mode