Stepping Numbers Problem
Description
LeetCode Problem 1215.
A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1.
- For example,
321is a stepping number while421is not.
Given two integers low and high, return a sorted list of all the stepping numbers in the inclusive range [low, high].
Example 1:
Input: low = 0, high = 21
Output: [0,1,2,3,4,5,6,7,8,9,10,12,21]
Example 2:
Input: low = 10, high = 15
Output: [10,12]
Constraints:
0 <= low <= high <= 2 * 10^9
Solution
Approach: BFS from the Single Digits
high can be 2 · 109, so checking every number in the range is far too slow. But stepping numbers are rare, and they are easy to build: take a stepping number, look at its last digit d, and append d - 1 or d + 1 (when that is still a digit). Every stepping number with two or more digits is made this way from the one without its last digit.
So start a queue with 1 to 9 and keep taking numbers out and putting their one or two children in. A breadth-first search produces the numbers in increasing order: all numbers with k digits come out before any with k + 1 digits, and among the same length, children are added in the order of their parents, smaller child first. Two consequences:
- The answer list comes out already sorted.
- As soon as a number larger than
highcomes out, everything still in the queue is larger too, so we can stop.
Numbers below low are skipped but still expanded, since their children may be in range. 0 is never produced by the queue (no number starts with a zero digit), so add it separately when low == 0.
The children of a number close to 2 · 109 are around 2 · 1010, which does not fit in a 32-bit int, so Java and C++ keep the queue in 64-bit integers.
Complexity: O(S) time and space, where S is the number of stepping numbers up to high (a few thousand at most), since each one is expanded once.
from collections import deque
class Solution:
def countSteppingNumbers(self, low: int, high: int) -> List[int]:
ans = [0] if low == 0 else []
# BFS from 1..9: numbers come out in increasing order (shorter first, then by value).
q = deque(range(1, 10))
while q:
v = q.popleft()
if v > high:
break # everything still queued is even bigger
if v >= low:
ans.append(v)
last = v % 10
if last > 0:
q.append(v * 10 + last - 1)
if last < 9:
q.append(v * 10 + last + 1)
return ans