Problem Description
Given two integers low and high, find and return a sorted list of all stepping numbers in the inclusive range [low, high]. A stepping number is an integer in which the absolute difference between every pair of adjacent digits is exactly 1.
Key Insights
- A stepping number has the property that for each adjacent pair of digits, their absolute difference is 1.
- Use a BFS (or DFS/backtracking) approach starting from each digit (0–9) to generate possible stepping number candidates.
- Special handle for 0 since it is a valid stepping number but does not lead to any larger candidate if used as a starting digit.
- Stop expanding a branch when the generated number exceeds high.
- The resulting list should be sorted (BFS approach inherently generates numbers in increasing order, but sorting at the end can be applied as a safeguard).
Space and Time Complexity
Time Complexity: O(2^L) where L is the number of digits in high. In practice, since L is small (at most 10 for high up to 2 * 10^9), the generation is efficient. Space Complexity: O(2^L) due to the BFS queue holding the generated numbers.
Solution
We use Breadth-First Search (BFS) to generate stepping numbers. Begin by adding the digits 0 through 9 (with a special check for 0 because it does not spawn children). For each number popped from the BFS queue, if it is within the range [low, high], add it to the result list. Then compute its last digit; based on that, generate potential next stepping numbers by appending (last_digit - 1) and (last_digit + 1) if they are valid. Continue this process until all possible candidates below or equal to high are generated. Finally, sort and return the result list.