Stepping Numbers

Given two integers ‘n’ and ‘m’, find all the stepping numbers in range [n, m]. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.

Examples:

Input : n = 0, m = 21
Output : 0 1 2 3 4 5 6 7 8 9 10 12 21

Input : n = 10, m = 15
Output : 10, 12

Method 1 : Brute force Approach

In this method, a brute force approach is used to iterate through all the integers from n to m and check if it’s a stepping number.

C++

// A C++ program to find all the Stepping Number in [n, m]
#include<bits/stdc++.h>
using namespace std;

// This function checks if an integer n is a Stepping Number
bool isStepNum(int n)
{
    // Initalize prevDigit with -1
    int prevDigit = -1;

    // Iterate through all digits of n and compare difference
    // between value of previous and current digits
    while (n)
    {
        // Get Current digit
        int curDigit = n % 10;

        // Single digit is consider as a
        // Stepping Number
        if (prevDigit == -1)
            prevDigit = curDigit;
        else
        {
            // Check if absolute difference between
            // prev digit and current digit is 1
            if (abs(prevDigit - curDigit) != 1)
                 return false;
        }
        prevDigit = curDigit;
        n /= 10;
    }

    return true;
}

// A brute force approach based function to find all
// stepping numbers.
void displaySteppingNumbers(int n, int m)
{
    // Iterate through all the numbers from [N,M]
    // and check if it’s a stepping number.
    for (int i=n; i<=m; i++)
        if (isStepNum(i))
            cout << i << " ";
}

// Driver program to test above function
int main()
{
    int n = 0, m = 21;

    // Display Stepping Numbers in
    // the range [n, m]
    displaySteppingNumbers(n, m);

    return 0;
}

Java

// A Java program to find all the Stepping Number in [n, m]
class Main
{
    // This Method checks if an integer n
    // is a Stepping Number
    public static boolean isStepNum(int n)
    {
        // Initalize prevDigit with -1
        int prevDigit = -1;

        // Iterate through all digits of n and compare
        // difference between value of previous and
        // current digits
        while (n > 0)
        {
            // Get Current digit
            int curDigit = n % 10;

            // Single digit is consider as a
            // Stepping Number
            if (prevDigit != -1)
            {
                // Check if absolute difference between
                // prev digit and current digit is 1
                if (Math.abs(curDigit-prevDigit) != 1)
                    return false;
            }
            n /= 10;
            prevDigit = curDigit;
        }
        return true;
    }

    // A brute force approach based function to find all
    // stepping numbers.
    public static void displaySteppingNumbers(int n,int m)
    {
        // Iterate through all the numbers from [N,M]
        // and check if it is a stepping number.
        for (int i = n; i <= m; i++)
            if (isStepNum(i))
                System.out.print(i+ " ");
    }

    // Driver code
    public static void main(String args[])
    {
        int n = 0, m = 21;

        // Display Stepping Numbers in the range [n,m]
        displaySteppingNumbers(n,m);
    }
}


Output:

0 1 2 3 4 5 6 7 8 9 10 12 21 

Method 2: Using BFS/DFS

The idea is to use a Breadth First Search/Depth First Search traversal.

How to build the graph?
Every node in the graph represents a stepping number; there will be a directed edge from a node U to V if V can be transformed from U. (U and V are Stepping Numbers) A Stepping Number V can be transformed from U in following manner.

lastDigit refers to the last digit of U (i.e. U % 10)
An adjacent number V can be:

  • U*10 + lastDigit + 1 (Neighbor A)
  • U*10 + lastDigit – 1 (Neighbor B)

By applying above operations a new digit is appended to U, it is either lastDigit-1 or lastDigit+1, so that the new number V formed from U is also a Stepping Number.
Therefore, every Node will have at most 2 neighboring Nodes.

Edge Cases: When the last digit of U is 0 or 9

Case 1: lastDigit is 0 : In this case only digit ‘1’ can be appended.
Case 2: lastDigit is 9 : In this case only digit ‘8’ can be appended.

What will be the source/starting Node?

  • Every single digit number is considered as a stepping Number, so bfs traversal for every digit will give all the stepping numbers starting from that digit.
  • Do a bfs/dfs traversal for all the numbers from [0,9].

Note: For node 0, no need to explore neighbors during BFS traversal since it will lead to 01, 012, 010 and these will be covered by the BFS traversal starting from node 1.

Example to find all the stepping numbers from 0 to 21

-> 0 is a stepping Number and it is in the range
   so display it.
-> 1 is a Stepping Number, find neighbors of 1 i.e.,
   10 and 12 and push them into the queue

How to get 10 and 12?
Here U is 1 and last Digit is also 1 
V = 10 + 0 = 10 ( Adding lastDigit - 1 )
V = 10 + 2 = 12 ( Adding lastDigit + 1 )

Then do the same for 10 and 12 this will result into
101, 123, 121 but these Numbers are out of range. 
Now any number transformed from 10 and 12 will result
into a number greater than 21 so no need to explore 
their neighbors.

-> 2 is a Stepping Number, find neighbors of 2 i.e. 
   21, 23.
-> 23 is out of range so it is not considered as a 
   Stepping Number (Or a neighbor of 2)

The other stepping numbers will be 3, 4, 5, 6, 7, 8, 9.

BFS based Solution:

C++

// A C++ program to find all the Stepping Number from N=n
// to m using BFS Approach
#include<bits/stdc++.h>
using namespace std;

// Prints all stepping numbers reachable from num
// and in range [n, m]
void bfs(int n, int m, int num)
{
    // Queue will contain all the stepping Numbers
    queue<int> q;

    q.push(num);

    while (!q.empty())
    {
        // Get the front element and pop from the queue
        int stepNum = q.front();
        q.pop();

        // If the Stepping Number is in the range
        // [n, m] then display
        if (stepNum <= m && stepNum >= n)
            cout << stepNum << " ";

        // If Stepping Number is 0 or greater than m,
        // need to explore the neighbors
        if (num == 0 || stepNum > m)
            continue;

        // Get the last digit of the currently visited
        // Stepping Number
        int lastDigit = stepNum % 10;

        // There can be 2 cases either digit to be
        // appended is lastDigit + 1 or lastDigit - 1
        int stepNumA = stepNum * 10 + (lastDigit- 1);
        int stepNumB = stepNum * 10 + (lastDigit + 1);

        // If lastDigit is 0 then only possible digit
        // after 0 can be 1 for a Stepping Number
        if (lastDigit == 0)
            q.push(stepNumB);

        //If lastDigit is 9 then only possible
        //digit after 9 can be 8 for a Stepping
        //Number
        else if (lastDigit == 9)
            q.push(stepNumA);

        else
        {
            q.push(stepNumA);
            q.push(stepNumB);
        }
    }
}

// Prints all stepping numbers in range [n, m]
// using BFS.
void displaySteppingNumbers(int n, int m)
{
    // For every single digit Number 'i'
    // find all the Stepping Numbers
    // starting with i
    for (int i = 0 ; i <= 9 ; i++)
        bfs(n, m, i);
}

//Driver program to test above function
int main()
{
    int n = 0, m = 21;

    // Display Stepping Numbers in the
    // range [n,m]
    displaySteppingNumbers(n,m);

    return 0;
}

Java

// A Java program to find all the Stepping Number in
// range [n, m]
import java.util.*;

class Main
{
    // Prints all stepping numbers reachable from num
    // and in range [n, m]
    public static void bfs(int n,int m,int num)
    {
        // Queue will contain all the stepping Numbers
        Queue<Integer> q = new LinkedList<Integer> ();

        q.add(num);

        while (!q.isEmpty())
        {
            // Get the front element and pop from
            // the queue
            int stepNum = q.poll();

            // If the Stepping Number is in
            // the range [n,m] then display
            if (stepNum <= m && stepNum >= n)
            {
                System.out.print(stepNum + " ");
            }

            // If Stepping Number is 0 or greater
            // then m ,need to explore the neighbors
            if (stepNum == 0 || stepNum > m)
                continue;

            // Get the last digit of the currently
            // visited Stepping Number
            int lastDigit = stepNum % 10;

            // There can be 2 cases either digit
            // to be appended is lastDigit + 1 or
            // lastDigit - 1
            int stepNumA = stepNum * 10 + (lastDigit- 1);
            int stepNumB = stepNum * 10 + (lastDigit + 1);

            // If lastDigit is 0 then only possible
            // digit after 0 can be 1 for a Stepping
            // Number
            if (lastDigit == 0)
                q.add(stepNumB);

            // If lastDigit is 9 then only possible
            // digit after 9 can be 8 for a Stepping
            // Number
            else if (lastDigit == 9)
                q.add(stepNumA);

            else
            {
                q.add(stepNumA);
                q.add(stepNumB);
            }
        }
    }

    // Prints all stepping numbers in range [n, m]
    // using BFS.
    public static void displaySteppingNumbers(int n,int m)
    {
        // For every single digit Number 'i'
        // find all the Stepping Numbers
        // starting with i
        for (int i = 0 ; i <= 9 ; i++)
            bfs(n, m, i);
    }

    //Driver code
    public static void main(String args[])
    {
        int n = 0, m = 21;

        // Display Stepping Numbers in
        // the range [n,m]
        displaySteppingNumbers(n,m);
    }
}

DFS based Solution

C++

// A C++ program to find all the Stepping Numbers
// in range [n, m] using DFS Approach
#include<bits/stdc++.h>
using namespace std;

// Prints all stepping numbers reachable from num
// and in range [n, m]
void dfs(int n, int m, int stepNum)
{
    // If Stepping Number is in the
    // range [n,m] then display
    if (stepNum <= m && stepNum >= n)
        cout << stepNum << " ";

    // If Stepping Number is 0 or greater
    // than m, then return
    if (stepNum == 0 || stepNum > m)
        return ;

    // Get the last digit of the currently
    // visited Stepping Number
    int lastDigit = stepNum % 10;

    // There can be 2 cases either digit
    // to be appended is lastDigit + 1 or
    // lastDigit - 1
    int stepNumA = stepNum*10 + (lastDigit-1);
    int stepNumB = stepNum*10 + (lastDigit+1);

    // If lastDigit is 0 then only possible
    // digit after 0 can be 1 for a Stepping
    // Number
    if (lastDigit == 0)
        dfs(n, m, stepNumB);

    // If lastDigit is 9 then only possible
    // digit after 9 can be 8 for a Stepping
    // Number
    else if(lastDigit == 9)
        dfs(n, m, stepNumA);
    else
    {
        dfs(n, m, stepNumA);
        dfs(n, m, stepNumB);
    }
}

// Method displays all the stepping
// numbers in range [n, m]
void displaySteppingNumbers(int n, int m)
{
    // For every single digit Number 'i'
    // find all the Stepping Numbers
    // starting with i
    for (int i = 0 ; i <= 9 ; i++)
        dfs(n, m, i);
}

//Driver program to test above function
int main()
{
    int n = 0, m = 21;

    // Display Stepping Numbers in
    // the range [n,m]
    displaySteppingNumbers(n,m);
    return 0;
}

Java

// A Java program to find all the Stepping Numbers
// in range [n, m] using DFS Approach
import java.util.*;

class Main
{
    // Method display's all the stepping numbers
    // in range [n, m]
    public static void dfs(int n,int m,int stepNum)
    {
        // If Stepping Number is in the
        // range [n,m] then display
        if (stepNum <= m && stepNum >= n)
            System.out.print(stepNum + " ");

        // If Stepping Number is 0 or greater
        // than m then return
        if (stepNum == 0 || stepNum > m)
            return ;

        // Get the last digit of the currently
        // visited Stepping Number
        int lastDigit = stepNum % 10;

        // There can be 2 cases either digit
        // to be appended is lastDigit + 1 or
        // lastDigit - 1
        int stepNumA = stepNum*10 + (lastDigit-1);
        int stepNumB = stepNum*10 + (lastDigit+1);

        // If lastDigit is 0 then only possible
        // digit after 0 can be 1 for a Stepping
        // Number
        if (lastDigit == 0)
            dfs(n, m, stepNumB);

        // If lastDigit is 9 then only possible
        // digit after 9 can be 8 for a Stepping
        // Number
        else if(lastDigit == 9)
            dfs(n, m, stepNumA);
        else
        {
            dfs(n, m, stepNumA);
            dfs(n, m, stepNumB);
        }
    }

    // Prints all stepping numbers in range [n, m]
    // using DFS.
    public static void displaySteppingNumbers(int n, int m)
    {
        // For every single digit Number 'i'
        // find all the Stepping Numbers
        // starting with i
        for (int i = 0 ; i <= 9 ; i++)
            dfs(n, m, i);
    }

    // Driver code
    public static void main(String args[])
    {
        int n = 0, m = 21;

        // Display Stepping Numbers in
        // the range [n,m]
        displaySteppingNumbers(n,m);
    }
}

Output:

0 1 10 12 2 21 3 4 5 6 7 8 9 

This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice





Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.