Count Stepping Numbers in Range - Problem

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 109 + 7.

Note: A stepping number should not have a leading zero.

Input & Output

Example 1 — Basic Range
$ Input: low = "0", high = "21"
Output: 13
💡 Note: Stepping numbers in [0,21]: 0,1,2,3,4,5,6,7,8,9,10,12,21. Count = 13
Example 2 — Single Digit Range
$ Input: low = "1", high = "9"
Output: 9
💡 Note: All single digits 1-9 are stepping numbers. Count = 9
Example 3 — Larger Range
$ Input: low = "10", high = "15"
Output: 2
💡 Note: Stepping numbers in [10,15]: 10,12. Count = 2

Constraints

  • 1 ≤ low.length, high.length ≤ 15
  • low and high consist of only digits
  • low ≤ high
  • low and high don't have leading zeros

Visualization

Tap to expand
Count Stepping Numbers in Range [10, 21]Range: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2110111213142123|1-0|=1 ✓|1-1|=0 ✗|1-2|=1 ✓|1-3|=2 ✗|1-4|=3 ✗|2-1|=1 ✓|2-3|=1 ✓Stepping Number: Adjacent digits differ by exactly 1Valid stepping numbers in range: 10, 12, 21Count = 3
Understanding the Visualization
1
Range
Given range [low, high] as strings
2
Check
Find numbers where |digit[i] - digit[i+1]| = 1
3
Count
Return count modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use digit DP to efficiently count stepping numbers without generating all of them
Asked in
Google 45 Meta 38 Amazon 32
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen