Problem solution · Python

Balanced K Factor Decomposition

Balanced K Factor Decomposition: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
120 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Balanced K Factor Decomposition, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 120 lines of Python from the credited upstream file balanced-k-factor-decomposition.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeBalanced K Factor Decomposition · PythonPython
Use this to learn the idea, then write your own version.
# Time:  precompute: O(rlogr)#        runtime:    O(k * (logn)^(k - 1))# Space: O(rlogr) import bisect  # backtracking, number theorydef factors(n):    result = [[] for _ in xrange(n+1)]    for i in xrange(1, n+1):        for j in range(i, n+1, i):            result[j].append(i)    return result  MAX_N = 10**5FACTORS = factors(MAX_N)class Solution(object):    def minDifference(self, n, k):        """        :type n: int        :type k: int        :rtype: List[int]        """        def backtracking(remain):            start = curr[-1] if curr else 1            if len(curr) == k-1 and remain >= start:                curr.append(remain)                if not result or result[-1]-result[0] > curr[-1]-curr[0]:                    result[:] = curr                curr.pop()                return            factors = FACTORS[remain]            for i in xrange(bisect.bisect_left(factors, start), len(factors)):                curr.append(factors[i])                backtracking(remain//factors[i])                curr.pop()                            result, curr = [], []        backtracking(n)        return result      # Time:  O(k * (n^(1/2) * n^(1/4) * n^(1/8) * n^(1/6) + n^(1/2) * n^(1/4) * n^(1/8) + n^(1/2) * n^(1/4) + n^(1/2))) <= O(k^2 * n)# Space: O(k)# backtracking, number theoryclass Solution2(object):    def minDifference(self, n, k):        """        :type n: int        :type k: int        :rtype: List[int]        """        def factors(n):            for i in xrange(1, n+1):                if i*i > n:                    break                if n%i:                    continue                yield i                if n//i != i:                    yield n//i         def backtracking(remain):            start = curr[-1] if curr else 1            if len(curr) == k-1 and remain >= start:                curr.append(remain)                if not result or result[-1]-result[0] > curr[-1]-curr[0]:                    result[:] = curr                curr.pop()                return            for i in factors(remain):                if i < start:                    continue                curr.append(i)                backtracking(remain//i)                curr.pop()                            result, curr = [], []        backtracking(n)        return result  # Time:  O(2^(k-1) * k * n)# Space: O(k)# backtracking, number theoryclass Solution3(object):    def minDifference(self, n, k):        """        :type n: int        :type k: int        :rtype: List[int]        """        def factors(n):            for i in xrange(1, n+1):                if i*i > n:                    break                if n%i:                    continue                yield i                if n//i != i:                    yield n//i         def backtracking(remain):            if len(curr) == k-1:                curr.append(remain)                if not result or max(result)-min(result) > max(curr)-min(curr):                    result[:] = curr                curr.pop()                return            for i in factors(remain):                curr.append(i)                backtracking(remain//i)                curr.pop()                            result, curr = [], []        backtracking(n)        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗