Count Stepping Numbers in Range Problem
Description
LeetCode Problem 2801.
Given two positive integers low and high represented as strings, find the count of stepping numbers in the inclusive range [low, high].
A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.
Return an integer denoting the count of stepping numbers in the inclusive range [low, high].
Since the answer may be very large, return it modulo 10^9 + 7.
Note: A stepping number should not have a leading zero.
Example 1:
Input: low = "1", high = "11"
Output: 10
Explanation: The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.
Example 2:
Input: low = "90", high = "101"
Output: 2
Explanation: The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2.
Constraints:
1 <= int(low) <= int(high) < 10^1001 <= low.length, high.length <= 100lowandhighconsist of only digits.lowandhighdon't have any leading zeros.
Solution
Approach: Digit DP
Count stepping numbers (adjacent digits differ by exactly 1) up to high, then up to low - 1, and subtract. Use a memoized DFS over the digits: dfs(pos, pre, lead, limit) where pre is the previous digit, lead says we are still in leading zeros, and limit says the prefix still equals the bound. At each position try the digits allowed by the limit; a leading zero keeps lead, and any other digit must differ from pre by 1 unless it is the first digit. Reaching the end counts as one number unless it was all zeros. Only states with no lead and no limit are cached. Everything is taken modulo 10^9 + 7, and low - 1 is computed on the string with big integers.
Complexity: O(10 * 10 * D) time and O(10 * D) space, where D is the number of digits of high.
from functools import lru_cache
class Solution:
def countSteppingNumbers(self, low: str, high: str) -> int:
@lru_cache(None)
def dfs(pos: int, pre: int, lead: bool, limit: bool) -> int:
if pos >= len(num):
return int(not lead)
up = int(num[pos]) if limit else 9
ans = 0
for i in range(up + 1):
if i == 0 and lead:
ans += dfs(pos + 1, pre, True, limit and i == up)
elif pre == -1 or abs(i - pre) == 1:
ans += dfs(pos + 1, i, False, limit and i == up)
return ans % mod
mod = 10**9 + 7
num = high
a = dfs(0, -1, True, True)
dfs.cache_clear()
num = str(int(low) - 1)
b = dfs(0, -1, True, True)
return (a - b) % mod