Optimal Account Balancing

HardBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A group of friends lent each other money. Each entry transactions[i] = [from, to, amount] means person from gave person to exactly amount dollars. Afterwards they want to settle up so that everyone's net balance is zero. A settlement transfer moves any positive amount from one person to another. Return the **minimum number of transfers** needed to settle all debts. Only each person's net balance matters, not who originally paid whom. Return 0 if everyone is already even.

Examples

Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
Net balances: person 0 paid 10 and got 5 back, so is owed 5; person 1 owes 10; person 2 is owed 5. Person 1 sends 5 to person 0 and 5 to person 2.
Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
Output: 1
Net balances: person 0 is owed 4, person 1 owes 4, person 2 is even. One transfer of 4 from 1 to 0 settles everything.

Constraints

  • 1 <= transactions.length <= 8
  • transactions[i].length == 3
  • 0 <= from, to < 12 and from != to
  • 1 <= amount <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems