#3791

Number of Balanced Integers in a Range

Hard
Dynamic ProgrammingDigit Dynamic ProgrammingRecursion with Memoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * d^2)
Space
O(1)
O(n * d^2)
💡

Intuition

Time O(n * d^2)Space O(n * d^2)

Using digit dynamic programming, we can efficiently count balanced integers up to a number by considering the sums of digits at odd and even positions recursively.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a recursive function that counts balanced integers up to a given number, maintaining the current position, sums of odd/even digits, and whether the number is still 'tight' to the original number.
  2. 2Step 2: Use memoization to store results for previously computed states to avoid redundant calculations.
  3. 3Step 3: Calculate f(high) - f(low - 1) to get the final count of balanced integers in the range.
solution.py14 lines
1def count_balanced(low, high):
2    def dp(pos, odd_sum, even_sum, tight, s):
3        if pos == len(s):
4            return 1 if odd_sum == even_sum else 0
5        if (pos, odd_sum, even_sum, tight) in memo:
6            return memo[(pos, odd_sum, even_sum, tight)]
7        limit = int(s[pos]) if tight else 9
8        count = 0
9        for digit in range(0, limit + 1):
10            count += dp(pos + 1, odd_sum + (digit if pos % 2 == 0 else 0), even_sum + (digit if pos % 2 == 1 else 0), tight and (digit == limit), s)
11        memo[(pos, odd_sum, even_sum, tight)] = count
12        return count
13    memo = {}
14    return dp(0, 0, 0, True, str(high)) - dp(0, 0, 0, True, str(low - 1))

Complexity note: The time complexity is O(n * d^2) where n is the number of digits and d is the range of possible sums, due to the recursive nature and memoization.

  • 1Balanced integers require at least two digits.
  • 2The position of digits matters for summation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.