Problem solution · Python

Number of Balanced Integers in a Range

Number of Balanced Integers in a Range: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
102 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

Dynamic programming

For Number of Balanced Integers in a Range, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 102 lines of Python from the credited upstream file number-of-balanced-integers-in-a-range.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

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 codeNumber of Balanced Integers in a Range · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O((logn)^2)# Space: O(logn) # dpclass Solution(object):    def countBalanced(self, low, high):        """        :type low: int        :type high: int        :rtype: int        """        def count(n):            digits = []            while n:                n, r = divmod(n, 10)                digits.append(r)            digits.reverse()            dp = [[0]*2 for _ in xrange(len(digits)*9+1)]            dp[0][1] = 1            for i in xrange(len(digits)):                new_dp = [[0]*2 for _ in xrange(len(digits)*9+1)]                for curr in xrange(len(dp)):                    curr -= len(digits)//2*9                    for tight in xrange(2):                        if not dp[curr][tight]:                            continue                        bound = digits[i] if tight else 9                        for d in xrange(bound+1):                            new_dp[curr-d if i&1 else curr+d][tight and d == bound] += dp[curr][tight]                dp = new_dp            return dp[0][0]                return count(high+1)-count(low)  # Time:  O((logn)^2)# Space: O((logn)^2)# memoizationclass Solution2(object):    def countBalanced(self, low, high):        """        :type low: int        :type high: int        :rtype: int        """        def count(n):            digits = []            while n:                n, r = divmod(n, 10)                digits.append(r)            digits.reverse()            memo = [[-1]*(len(digits)*9+1) for _ in xrange(len(digits))]            def memoization(i, curr, tight):                if i == len(digits):                    return curr == 0                if not tight and memo[i][curr] != -1:                    return memo[i][curr]                bound = digits[i] if tight else 9                result = 0                for d in xrange(bound+1):                    result += memoization(i+1, curr-d if i&1 else curr+d, tight and d == bound)                if not tight:                    memo[i][curr] = result                return result                        return memoization(0, 0, True)                return count(high)-count(low-1)  # Time:  O((logn)^2)# Space: O((logn)^2)# memoizationclass Solution3(object):    def countBalanced(self, low, high):        """        :type low: int        :type high: int        :rtype: int        """        def count(n):            digits = []            while n:                n, r = divmod(n, 10)                digits.append(r)            digits.reverse()            memo = [[[-1]*2 for _ in xrange(len(digits)*9+1)] for _ in xrange(len(digits))]            def memoization(i, curr, tight):                if i == len(digits):                    return int(curr == 0)                if memo[i][curr][tight] == -1:                    bound = digits[i] if tight else 9                    result = 0                    for d in xrange(bound+1):                        result += memoization(i+1, curr-d if i&1 else curr+d, tight and d == bound)                    memo[i][curr][tight] = result                return memo[i][curr][tight]                        return memoization(0, 0, True)                return count(high)-count(low-1) 

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 ↗