Optimal Account Balancing — LeetCode 465 Python Solution

HardLeetCode PremiumBit ManipulationArrayDynamic ProgrammingBacktrackingBitmask
Problem
#465
Reading time
4 min

The 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.

Example

Input
transactions = [[0,1,10],[2,0,5]]
Output
2
Explanation
Person #0 gave person #1 $10.

Python solution

Python
class Solution:
    def minTransfers(self, transactions: List[List[int]]) -> int:
        g = defaultdict(int)
        for f, t, x in transactions:
            g[f] -= x
            g[t] += x
        nums = [x for x in g.values() if x]
        m = len(nums)
        f = [inf] * (1 << m)
        f[0] = 0
        for i in range(1, 1 << m):
            s = 0
            for j, x in enumerate(nums):
                if i >> j & 1:
                    s += x
            if s == 0:
                f[i] = i.bit_count() - 1
                j = (i - 1) & i
                while j > 0:
                    f[i] = min(f[i], f[j] + f[i ^ j])
                    j = (j - 1) & i
        return f[-1]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 465. Optimal Account Balancing is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 465. Optimal Account Balancing?
LeetCode 465. Optimal Account Balancing is rated Hard on LeetCode.
What topics does LeetCode 465. Optimal Account Balancing cover?
LeetCode 465. Optimal Account Balancing is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.
Is LeetCode 465. Optimal Account Balancing a premium problem?
Yes. LeetCode 465. Optimal Account Balancing is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview