Count Good Integers in a Range Problem
Description
LeetCode Problem 3966.
You are given three integers l, r and k.
A number is considered good if the absolute difference between every pair of adjacent digits is at most k.
Return the number of good integers in the range [l, r] (inclusive).
The absolute difference between values x and y is defined as abs(x - y).
Example 1:
Input: l = 10, r = 15, k = 1
Output: 3
Explanation:
- The good integers in the range are 10, 11, and 12.
- For 10, abs(1 - 0) = 1.
- For 11, abs(1 - 1) = 0.
- For 12, abs(1 - 2) = 1.
- All these differences are at most k = 1. Thus, the answer is 3.
Example 2:
Input: l = 201, r = 204, k = 2
Output: 2
Explanation:
- The good integers in the range are 201 and 202.
- For 201, abs(2 - 0) = 2 and abs(0 - 1) = 1.
- For 202, abs(2 - 0) = 2 and abs(0 - 2) = 2.
- Thus, the answer is 2.
Constraints:
10 <= l <= r <= 10^150 <= k <= 9
Solution
Approach: Digit DP
r can be 1015, so we cannot test every integer. A number is good when each pair of neighboring digits differs by at most k, and that is a property we can count digit by digit.
Let count(n) be the number of good integers in [1, n]. The answer is count(r) - count(l - 1).
First precompute f[m][d], the number of good digit strings of length m that start with digit d. A string of length 1 is always good, so f[1][d] = 1, and f[m][d] is the sum of f[m-1][e] over every digit e with |d - e| <= k.
To compute count(n), write n in decimal with m digits:
- Every number with fewer than
mdigits is belown. For each lengthlen < m, addf[len][d]for the first digitdfrom 1 to 9. - For numbers with exactly
mdigits, walk through the digits ofnfrom left to right. At positioni, try each digitcsmaller thann[i](at least 1 for the first position). Ifcis withinkof the previous digit, every continuation is free, so addf[m - i][c]. - Then keep following
nitself. Ifn[i]differs from the previous digit by more thank,nand everything below this prefix is already counted, so stop. If we get through all digits,nis good and we add 1.
Complexity: O(log n * 10 * 10) time for both the table and the two counts, and O(log n * 10) space.
class Solution:
def goodIntegers(self, l: int, r: int, k: int) -> int:
# f[m][d] = number of good digit strings of length m that start with digit d
f = [[0] * 10 for _ in range(18)]
for d in range(10):
f[1][d] = 1
for m in range(2, 18):
for d in range(10):
f[m][d] = sum(f[m - 1][e] for e in range(10) if abs(d - e) <= k)
def count(n: int) -> int: # good integers in [1, n]
if n <= 0:
return 0
s = str(n)
m = len(s)
res = 0
for length in range(1, m):
res += sum(f[length][1:])
prev = -1
for i, ch in enumerate(s):
x = int(ch)
for c in range(1 if i == 0 else 0, x):
if i == 0 or abs(c - prev) <= k:
res += f[m - i][c]
if i > 0 and abs(x - prev) > k:
return res
prev = x
return res + 1 # n itself is good
return count(r) - count(l - 1)