Stepping Numbers - Problem

A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.

For example, 321 is a stepping number while 421 is not.

Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].

Input & Output

Example 1 — Basic Range
$ Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]
💡 Note: All single digits 0-9 are stepping numbers. For two digits: 10 (|1-0|=1), 12 (|1-2|=1), and 21 (|2-1|=1) are valid. Numbers like 11, 13, 14, etc. are invalid as adjacent digits don't differ by 1.
Example 2 — Higher Range
$ Input: low = 10, high = 15
Output: [10,12]
💡 Note: In range [10,15]: 10 has digits 1,0 with |1-0|=1 ✓. 12 has digits 1,2 with |1-2|=1 ✓. Numbers 11,13,14,15 don't satisfy the stepping property.
Example 3 — Single Range
$ Input: low = 90, high = 101
Output: [101]
💡 Note: Only 101 is a stepping number in this range: digits 1,0,1 have differences |1-0|=1 and |0-1|=1, both equal to 1.

Constraints

  • 0 ≤ low ≤ high ≤ 2 × 109

Visualization

Tap to expand
Stepping Numbers - DFS Recursive Generation INPUT Range: [low, high] 0 21 Stepping Number Rule: Adjacent digits differ by 1 321: |3-2|=1, |2-1|=1 OK Examples: 12 21 13 42 Input Values: low = 0 high = 21 ALGORITHM STEPS 1 Initialize Seeds Start DFS from digits 1-9 (0 handled separately) 2 DFS Recursion For each num, try appending: lastDigit-1 or lastDigit+1 3 Check Bounds If num in [low,high]: add If num > high: stop branch 4 Sort Results Collect all valid numbers Sort in ascending order DFS Tree (from seed 1): 1 10 12 21 FINAL RESULT Stepping Numbers Found: 0 1 2 3 4 5 6 7 8 9 10 12 21 Output Array: [0,1,2,3,4,5,6,7,8,9, 10,12,21] OK - 13 Numbers Found All in range [0, 21] Complexity: Time: O(2^n), Space: O(n) Key Insight: DFS generates stepping numbers by exploring digit sequences where each new digit differs by exactly 1 from the previous. Starting from seeds 1-9, we recursively build: num*10 + (lastDigit +/- 1). This avoids checking every number in the range - we only generate valid stepping numbers! TutorialsPoint - Stepping Numbers | DFS - Recursive Generation
Asked in
Google 45 Amazon 35 Microsoft 28
32.4K Views
Medium Frequency
~25 min Avg. Time
856 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