1215. Stepping Numbers π
Description
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 * 109
Solutions
Solution 1: BFS
Thinking
\(high\) can be \(2\times 10^9\), so testing every integer is impossible. A stepping number's next digit is only last-digit \(\pm 1\), so we grow them from \(1\sim 9\) by BFS; the count is far smaller than the value range.
The queue is increasing; we stop past \(high\) and keep values in \([low,high]\). Zero is handled separately. BFS both emits in order and avoids duplicates.
First, if \(low\) is \(0\), we need to add \(0\) to the answer.
Next, we create a queue \(q\) and add \(1 \sim 9\) to the queue. Then, we repeatedly take out elements from the queue. Let the current element be \(v\). If \(v\) is greater than \(high\), we stop searching. If \(v\) is in the range \([low, high]\), we add \(v\) to the answer. Then, we need to record the last digit of \(v\) as \(x\). If \(x \gt 0\), we add \(v \times 10 + x - 1\) to the queue. If \(x \lt 9\), we add \(v \times 10 + x + 1\) to the queue. Repeat the above steps until the queue is empty.
The time complexity is \(O(10 \times 2^{\log M})\), and the space complexity is \(O(2^{\log M})\), where \(M\) is the number of digits in \(high\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |