Number of Balanced Integers in a Range Problem
Description
LeetCode Problem 3791.
You are given two integers low and high.
An integer is called balanced if it satisfies both of the following conditions:
- It contains at least two digits.
- The sum of digits at even positions is equal to the sum of digits at odd positions (the leftmost digit has position 1).
Return an integer representing the number of balanced integers in the range [low, high] (both inclusive).
Example 1:
Input: low = 1, high = 100
Output: 9
Explanation:
The 9 balanced numbers between 1 and 100 are 11, 22, 33, 44, 55, 66, 77, 88, and 99.
Example 2:
Input: low = 120, high = 129
Output: 1
Explanation:
Only 121 is balanced because the sum of digits at even and odd positions are both 2.
Example 3:
Input: low = 1234, high = 1234
Output: 0
Explanation:
1234 is not balanced because the sum of digits at odd positions (1 + 3 = 4) does not equal the sum at even positions (2 + 4 = 6).
Constraints:
1 <= low <= high <= 10^15
Solution
Approach: Digit DP
We count balanced numbers in [1, x] for x = high and x = low - 1 and subtract. Counting up to x is a standard digit DP: build the number digit by digit from the left, tracking
pos: the digit we are filling,diff: the sum of digits at odd positions minus the sum at even positions,lim: whether the digits so far equal the prefix ofx, which caps the next digit at the digit ofx(otherwise it is9).
When all digits are placed, the number is balanced if diff == 0. Results for states with lim = false are memoized, since they no longer depend on x.
Leading zeros do not matter: swapping which positions count as odd or even keeps diff == 0 true, and zeros add nothing. The only side effects are that the number 0 is counted and that single-digit numbers are never balanced. To keep the subtraction exact we first raise low to at least 11 (and return 0 if high < 11), since no number below 11 is balanced.
Complexity: with D = 10 digit choices and L ≈ 16 digits, there are O(L * L * 9) distinct states, so about O(D * L2 * 9) time and O(L2) extra space.
from functools import lru_cache
class Solution:
def countBalanced(self, low: int, high: int) -> int:
@lru_cache(None)
def dfs(pos: int, diff: int, lim: int) -> int:
if pos >= len(num):
return 1 if diff == 0 else 0
res = 0
up = int(num[pos]) if lim else 9
for i in range(up + 1):
res += dfs(
pos + 1, diff + i * (1 if pos % 2 == 0 else -1), lim and i == up
)
return res
if high < 11:
return 0
low = max(low, 11)
num = str(low - 1)
a = dfs(0, 0, True)
dfs.cache_clear()
num = str(high)
b = dfs(0, 0, True)
return b - a