{x}
blog image

Stepping Numbers

Solution Explanation: Stepping Numbers

The problem asks to find all stepping numbers within a given range [low, high]. A stepping number is defined as an integer where the absolute difference between any two adjacent digits is exactly 1. The solution employs a Breadth-First Search (BFS) approach for efficiency.

Approach: Breadth-First Search (BFS)

  1. Handle the Base Case: If low is 0, add 0 to the result list immediately, as 0 is a stepping number.

  2. Initialization: Create a queue q to store stepping numbers. Initialize it with single-digit numbers (1 to 9).

  3. BFS Iteration: The core of the algorithm lies in the BFS loop. We repeatedly dequeue a number v from the queue and perform the following:

    • Check Bounds: If v exceeds high, we break the loop because all subsequent numbers generated will also be greater than high.

    • Add to Result: If v is within the range [low, high], add it to the result list ans.

    • Generate Next Stepping Numbers: The crucial step is generating the next stepping numbers from v. Let x be the last digit of v.

      • If x > 0, we can append x - 1 to v to create a new stepping number (v * 10 + x - 1).
      • If x < 9, we can append x + 1 to v to create another new stepping number (v * 10 + x + 1). These new numbers are added to the queue for exploration in subsequent iterations.
  4. Return Result: Once the queue is empty (all reachable stepping numbers have been processed), the sorted ans list is returned.

Time and Space Complexity Analysis

Time Complexity: The time complexity is not easily expressed with a standard Big O notation because it depends on the distribution of stepping numbers within the given range. In the worst-case scenario (a very large range with many stepping numbers), the time complexity is approximately O(B), where B is the number of stepping numbers generated. In the average case, it's considerably less. Generating stepping numbers using BFS avoids redundant computations significantly.

Space Complexity: The space complexity is O(B), where B is the number of stepping numbers generated and stored in the queue at any given time. This is because the queue holds the numbers currently being processed. In the worst case, the queue's size could become large, but it is still bounded by the number of stepping numbers within the range.

Code Examples (Multiple Languages)

The code implementations provided earlier demonstrate the BFS approach in several languages. All versions follow the same fundamental algorithm:

  • They initialize the queue with single-digit stepping numbers.
  • They iteratively dequeue, check bounds, add to the result, and generate new stepping numbers.

The slight variations across the languages primarily reflect differences in syntax and data structures (e.g., deque in Python vs. ArrayDeque in Java). However, the underlying logic remains consistent.