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 INPUT Range [0, 21] 0 5 10 15 21 Stepping Numbers: 0 1 10 12 21 ... Example: 12 1 2 |2-1| = 1 OK Input Values: low = "0" high = "21" ALGORITHM STEPS (DP) 1 Digit DP Setup Define state: pos, lastDigit, tight, started flags 2 Count up to high f(high) = stepping nums in range [0, high] 3 Count up to low-1 f(low-1) = stepping nums in range [0, low-1] 4 Subtract Results Answer = f(high) - f(low-1) mod (10^9 + 7) DP Transition: For digit d at position i: next digit must be d+1 or d-1 d --> d+1 d-1 (if valid: 0-9, no leading 0) FINAL RESULT Stepping Numbers in [0,21]: 0 1 2 3 4 5 6 7 8 9 10 12 21 Single digits: 10 (0-9) Two digits: 10, 12, 21 Output: 13 Verification: f("21") = 13 stepping nums f("-1") = 0 (no negatives) 13 - 0 = 13 OK Key Insight: Digit DP allows counting numbers with digit constraints without iterating through all values. State: (position, last_digit, is_tight, has_started). Transition: place digits d-1 or d+1 only. Time: O(len * 10 * 2 * 2) per number. Use inclusion-exclusion: f(high) - f(low-1). TutorialsPoint - Count Stepping Numbers in Range | Digit DP Approach
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