Count Stepping Numbers in Range - Problem
Imagine you're a mathematician studying a special type of number called a stepping number. These are fascinating integers where each adjacent digit differs by exactly 1 - like climbing stairs digit by digit!
A stepping number is an integer where all adjacent digits have an absolute difference of exactly 1. For example:
123is a stepping number (|2-1|=1, |3-2|=1)4321is a stepping number (|3-4|=1, |2-3|=1, |1-2|=1)456is NOT a stepping number (|5-4|=1 ✓, but |6-5|=1 ✓ - wait, this IS stepping!)135is NOT a stepping number (|3-1|=2 ≠ 1)
Given two positive integers low and high represented as strings (because they can be very large!), your mission is to count all stepping numbers in the inclusive range [low, high].
Important: Stepping numbers cannot have leading zeros (so 01, 012 are invalid).
Since the answer can be astronomically large, return it modulo 109 + 7.
Input & Output
example_1.py — Basic Range
$
Input:
low = "1", high = "11"
›
Output:
10
💡 Note:
The stepping numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. All single digits are stepping numbers by definition, and 10 is stepping because |1-0|=1.
example_2.py — Larger Range
$
Input:
low = "90", high = "101"
›
Output:
2
💡 Note:
The stepping numbers in this range are: 98 (|9-8|=1) and 101 (|0-1|=1, |1-0|=1). Note that 90, 91, 92, etc. are not stepping numbers because the difference between adjacent digits is not 1.
example_3.py — Single Number
$
Input:
low = "123", high = "123"
›
Output:
1
💡 Note:
Only checking the number 123. Since |2-1|=1 and |3-2|=1, it is a stepping number, so the count is 1.
Constraints
- 1 ≤ low.length, high.length ≤ 100
- low and high consist of only digits
- low and high don't have leading zeros
- low ≤ high
- Answer fits in 32-bit integer after taking modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Start the staircase
Begin with any digit 1-9 (no leading zeros)
2
Add valid steps
From digit d, we can only go to d-1 or d+1 (if they exist)
3
Track boundaries
Ensure we stay within the [low, high] range using tight bounds
4
Count valid paths
Sum all complete staircases that form valid stepping numbers
Key Takeaway
🎯 Key Insight: Use Digit DP to build stepping numbers systematically, avoiding the need to check every number in the potentially huge range!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code