Leetcode #2801: Count Stepping Numbers in Range
In this guide, we solve Leetcode #2801 Count Stepping Numbers in Range in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
class Solution:
def countSteppingNumbers(self, low: str, high: str) -> int:
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
Complexity
The time complexity is , and the space complexity is , where represents the size of the number , and represents the digit set. The space complexity is , where represents the size of the number , and represents the digit set.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.