Stepping Numbers

medium math bfs number theory

Problem

A stepping number is an integer where all of its adjacent digits differ by 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 stepping numbers in the inclusive range [low, high]. Single-digit numbers (0–9) are stepping numbers.

Inputlow = 0, high = 21
Output[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21]
10 (1→0 differ by 1), 12 (1→2) and 21 (2→1) qualify; 11 does not because 1→1 differs by 0.

from collections import deque

def stepping_numbers(low, high):
    res = []
    if low == 0:
        res.append(0)
    queue = deque(range(1, 10))
    while queue:
        num = queue.popleft()
        if num > high:
            continue
        if num >= low:
            res.append(num)
        last = num % 10
        if last > 0:
            queue.append(num * 10 + last - 1)
        if last < 9:
            queue.append(num * 10 + last + 1)
    return sorted(res)
function steppingNumbers(low, high) {
  const res = [];
  if (low === 0) res.push(0);
  const queue = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  while (queue.length) {
    const num = queue.shift();
    if (num > high) continue;
    if (num >= low) res.push(num);
    const last = num % 10;
    if (last > 0) queue.push(num * 10 + last - 1);
    if (last < 9) queue.push(num * 10 + last + 1);
  }
  return res.sort((a, b) => a - b);
}
class Solution {
    public List<Integer> steppingNumbers(int low, int high) {
        List<Integer> res = new ArrayList<>();
        if (low == 0) res.add(0);
        Queue<Long> queue = new LinkedList<>();
        for (int d = 1; d <= 9; d++) queue.add((long) d);
        while (!queue.isEmpty()) {
            long num = queue.poll();
            if (num > high) continue;
            if (num >= low) res.add((int) num);
            long last = num % 10;
            if (last > 0) queue.add(num * 10 + last - 1);
            if (last < 9) queue.add(num * 10 + last + 1);
        }
        Collections.sort(res);
        return res;
    }
}
vector<int> steppingNumbers(int low, int high) {
    vector<int> res;
    if (low == 0) res.push_back(0);
    queue<long> q;
    for (int d = 1; d <= 9; d++) q.push(d);
    while (!q.empty()) {
        long num = q.front(); q.pop();
        if (num > high) continue;
        if (num >= low) res.push_back((int) num);
        long last = num % 10;
        if (last > 0) q.push(num * 10 + last - 1);
        if (last < 9) q.push(num * 10 + last + 1);
    }
    sort(res.begin(), res.end());
    return res;
}
Time: O(k log k) Space: O(k)