KatInterview

465. Optimal Account Balancing

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of transactions to settle all debts among a group of people. The initial transactions describe who owes whom, but multiple transactions can be consolidated. For example, if A owes B $10 and B owes A $5, this is equivalent to A just paying B $5.

Solution

Optimal Account Balancing in Python

class Solution:
    def minTransfers(self, transactions: List[List[int]]) -> int:
        balances = collections.defaultdict(int)
        for u, v, amount in transactions:
            balances[u] -= amount
            balances[v] += amount
        
        debts = [balance for balance in balances.values() if balance != 0]
        if not debts:
            return 0
            
        return self.dfs(0, debts)

    def dfs(self, start_index: int, debts: List[int]) -> int:
        # Skip people who are already settled (balance is 0)
        while start_index < len(debts) and debts[start_index] == 0:
            start_index += 1

        # Base case: if all people from this point are settled, we are done
        if start_index == len(debts):
            return 0

        min_transactions = float('inf')

        # Try to settle debts[start_index] by transferring their balance to another person i
        for i in range(start_index + 1, len(debts)):
            # A transaction can consolidate debts of the same sign or cancel debts of opposite signs.
            # Both are valid moves. To find the minimum, we must explore all possibilities.
            # The optimization `if debts[i] * debts[start_index] < 0:` can prune the search space but is not
            # strictly necessary for correctness and can be complex to reason about its optimality in all cases.
            # The core idea is one person is settled, reducing the problem size by one.
            debts[i] += debts[start_index]
            min_transactions = min(min_transactions, 1 + self.dfs(start_index + 1, debts))
            debts[i] -= debts[start_index]  # Backtrack
            
        return min_transactions

Optimal Account Balancing in Java

class Solution {
    public int minTransfers(int[][] transactions) {
        Map<Integer, Integer> balances = new HashMap<>();
        for (int[] t : transactions) {
            balances.put(t[0], balances.getOrDefault(t[0], 0) - t[2]);
            balances.put(t[1], balances.getOrDefault(t[1], 0) + t[2]);
        }

        List<Integer> debts = new ArrayList<>();
        for (int balance : balances.values()) {
            if (balance != 0) {
                debts.add(balance);
            }
        }

        return dfs(0, debts);
    }

    private int dfs(int start_index, List<Integer> debts) {
        // Skip people who are already settled (balance is 0)
        while (start_index < debts.size() && debts.get(start_index) == 0) {
            start_index++;
        }

        // Base case: if we have processed all people, no more transactions are needed
        if (start_index == debts.size()) {
            return 0;
        }

        int min_transactions = Integer.MAX_VALUE;

        // Try to settle debts[start_index] by transferring their balance to another person i
        for (int i = start_index + 1; i < debts.size(); i++) {
            // The transaction: person at start_index gives their balance to person at i.
            // This settles person at start_index.
            // We try all possible 'i' to find the minimum number of subsequent transactions.
            // The optimization of checking `debts[start_index] * debts[i] < 0` can prune the search tree
            // but can be tricky to get right. The simplest brute-force is to try every person.
            int currentVal = debts.get(i);
            int startVal = debts.get(start_index);
            debts.set(i, currentVal + startVal);
            min_transactions = Math.min(min_transactions, 1 + dfs(start_index + 1, debts));
            debts.set(i, currentVal); // Backtrack
        }

        return min_transactions;
    }
}

Optimal Account Balancing in C++

class Solution {
public:
    int minTransfers(vector<vector<int>>& transactions) {
        unordered_map<int, int> balances;
        for (const auto& t : transactions) {
            balances[t[0]] -= t[2];
            balances[t[1]] += t[2];
        }

        vector<int> debts;
        for (const auto& pair : balances) {
            if (pair.second != 0) {
                debts.push_back(pair.second);
            }
        }

        return dfs(0, debts);
    }

private:
    int dfs(int start_index, vector<int>& debts) {
        // Skip people who are already settled
        while (start_index < debts.size() && debts[start_index] == 0) {
            start_index++;
        }

        // Base case: all debts are settled
        if (start_index == debts.size()) {
            return 0;
        }

        int min_transactions = INT_MAX;

        // Try to settle debts[start_index] with every other person
        for (int i = start_index + 1; i < debts.size(); ++i) {
            // Optimization: if two people have opposite balances, 
            // combining them might not be necessary, but it's a valid move.
            // A key insight is that to minimize transactions, we should try to zero out balances.
            // If debts[i] and debts[start_index] have opposite signs, it's a debtor paying a creditor.
            // If they have same signs, it's consolidating debts/credits.
            // The logic holds for both cases because we are abstracting a transaction
            // as moving a balance obligation.
            // To ensure correctness, we must try all pairs.
            if (debts[start_index] * debts[i] < 0) { // A small optimization, not strictly required for correctness but prunes the search space.
                debts[i] += debts[start_index]; // Person start_index's balance is transferred to person i
                min_transactions = min(min_transactions, 1 + dfs(start_index + 1, debts));
                debts[i] -= debts[start_index]; // Backtrack
            }
        }
        
        // If no optimal pairing was found (e.g. all remaining have same sign), we still need to resolve them.
        // So we need a fallback to the full search if the optimization is used.
        // A simpler, always correct approach is to not check the sign.
        if (min_transactions == INT_MAX) {
            for (int i = start_index + 1; i < debts.size(); ++i) {
                 debts[i] += debts[start_index];
                 min_transactions = min(min_transactions, 1 + dfs(start_index + 1, debts));
                 debts[i] -= debts[start_index];
            }
        }

        return min_transactions == INT_MAX ? 0 : min_transactions;
    }
};

Optimal Account Balancing in TypeScript

function minTransfers(transactions: number[][]): number {
    const balances: Map<number, number> = new Map();
    for (const [from, to, amount] of transactions) {
        balances.set(from, (balances.get(from) || 0) - amount);
        balances.set(to, (balances.get(to) || 0) + amount);
    }

    const debts: number[] = [];
    for (const balance of balances.values()) {
        if (balance !== 0) {
            debts.push(balance);
        }
    }

    if (debts.length === 0) {
        return 0;
    }

    function dfs(startIndex: number, currentDebts: number[]): number {
        // Skip people who are already settled
        while (startIndex < currentDebts.length && currentDebts[startIndex] === 0) {
            startIndex++;
        }

        // Base case: All debts are settled
        if (startIndex === currentDebts.length) {
            return 0;
        }

        let minTransactions = Infinity;

        // Try to settle currentDebts[startIndex] with every other person
        for (let i = startIndex + 1; i < currentDebts.length; i++) {
            // The transaction: person at startIndex gives their balance to person at i.
            // This settles person at startIndex.
            // We try all possible 'i' to find the minimum number of subsequent transactions.
            const originalValue = currentDebts[i];
            currentDebts[i] += currentDebts[startIndex];
            minTransactions = Math.min(minTransactions, 1 + dfs(startIndex + 1, currentDebts));
            currentDebts[i] = originalValue; // Backtrack
        }

        return minTransactions;
    }

    return dfs(0, debts);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.