Optimal Account Balancing - Problem

You are given an array of transactions transactions where transactions[i] = [fromi, toi, amounti] indicates that the person with ID = fromi gave amounti $ to the person with ID = toi.

Return the minimum number of transactions required to settle the debt.

A debt is settled when the net balance of each person becomes zero. Multiple transactions between the same people are allowed.

Input & Output

Example 1 — Basic Three Person Settlement
$ Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
💡 Note: Person 0 gave $10 to person 1 and received $5 from person 2. Net balances: Person 0: -$5, Person 1: +$10, Person 2: -$5. Person 1 pays $5 to person 0, and person 1 pays $5 to person 2. Minimum 2 transactions needed.
Example 2 — Already Settled
$ Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output: 1
💡 Note: Net balances: Person 0: -$5, Person 1: +$4, Person 2: $0, Person 0 (unnamed): +$1. After calculating all balances, only 1 transaction needed to settle remaining debts.
Example 3 — No Settlements Needed
$ Input: transactions = [[0,1,5],[1,2,5],[2,0,5]]
Output: 0
💡 Note: This forms a cycle: person 0 → person 1 → person 2 → person 0. All net balances are zero, so no additional transactions needed.

Constraints

  • 1 ≤ transactions.length ≤ 8
  • transactions[i].length == 3
  • 0 ≤ fromi, toi < 12
  • fromi ≠ toi
  • 1 ≤ amounti ≤ 100

Visualization

Tap to expand
Optimal Account Balancing INPUT Transactions Array: [[0,1,10], [2,0,5]] Transaction Graph: 0 1 2 $10 $5 Net Balances: P0: -10+5 = -5 P1: +10, P2: -5 ALGORITHM STEPS 1 Calculate Net Balances Sum in/out for each person 2 Filter Non-Zero Debts Remove settled accounts 3 Backtrack with Pruning Try settling pairs optimally 4 Find Minimum Transfers Return optimal count Debt Array: -5 +10 -5 Pruning: Skip same-sign pairs Match opposite signs only FINAL RESULT Optimal Settlement: Transfer 1: 0 $5 1 Transfer 2: 2 $5 1 Output: 2 [OK] All debts settled with 2 transactions Key Insight: Calculate net balances first, then use backtracking to find minimum transfers. Prune by only matching opposite-sign debts. When a debt becomes zero, we've found one valid transfer. Time complexity: O(n!) in worst case, but pruning significantly reduces practical runtime. TutorialsPoint - Optimal Account Balancing | Optimized Backtracking with Pruning
Asked in
Intuit 15 Uber 8 PayPal 6
22.0K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen