Count Evenly Good Integers Problem
Description
LeetCode Problem 4060.
You are given two integers l and r.
An integer is called evenly good if it contains an even number of even digits.
Return the number of evenly good integers in the inclusive range [l, r].
Example 1:
Input: l = 18, r = 22
Output: 3
Explanation:
The evenly good integers in the range [18, 22] are:
- 19, because it contains 0 even digits.
- 20, because it contains 2 even digits.
- 22, because it contains 2 even digits.
Thus, the answer is 3.
Example 2:
Input: l = 98, r = 101
Output: 2
Explanation:
The evenly good integers in the range [98, 101] are:
- 99, because it contains 0 even digits.
- 100, because it contains 2 even digits.
Thus, the answer is 2.
Example 3:
Input: l = 1, r = 10
Output: 5
Explanation:
The evenly good integers in the range [1, 10] are 1, 3, 5, 7, and 9, because each of them contains 0 even digits. Thus, the answer is 5.
Constraints:
1 <= l <= r <= 10^15
Solution
Approach: Digit DP
Let F(x) be the number of evenly good integers in [1, x]. The answer is F(r) - F(l - 1).
Write x as a decimal string and build numbers digit by digit from the most significant digit, with memoization on four things: the position, the parity of the even digits so far, whether the prefix is still equal to the prefix of x (tight), and whether the number has started (leading zeros are not digits, so they must not be counted as even digits).
At the end of the string, a number counts when it has started and the parity is 0. A digit d flips the parity when it is even. While the number has not started, choosing 0 just keeps it unstarted.
There are at most 16 digits, so the state space is tiny.
Complexity: O(10 * log r) time and O(log r) space.
from functools import lru_cache
class Solution:
def countEvenlyGoodIntegers(self, l: int, r: int) -> int:
def count(x: int) -> int:
# numbers in [1, x] with an even number of even digits
if x <= 0:
return 0
s = str(x)
@lru_cache(None)
def dfs(pos: int, parity: int, tight: bool, started: bool) -> int:
if pos == len(s):
return 1 if started and parity == 0 else 0
up = int(s[pos]) if tight else 9
res = 0
for d in range(up + 1):
if not started and d == 0:
res += dfs(pos + 1, 0, tight and d == up, False)
else:
res += dfs(pos + 1, (parity + (d + 1) % 2) % 2, tight and d == up, True)
return res
return dfs(0, 0, True, False)
return count(r) - count(l - 1)