Open In App

Print all Jumping Numbers smaller than or equal to a given value

Last Updated : 01 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A number is called as a Jumping Number if all adjacent digits in it differ by 1. The difference between ‘9’ and ‘0’ is not considered as 1. 
All single digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are Jumping numbers but 796 and 89098 are not. 
Given a positive number x, print all Jumping Numbers smaller than or equal to x. The numbers can be printed in any order.

Example: 

Input: x = 20
Output:  0 1 2 3 4 5 6 7 8 9 10 12

Input: x = 105
Output:  0 1 2 3 4 5 6 7 8 9 10 12
         21 23 32 34 43 45 54 56 65
         67 76 78 87 89 98 101

Note: Order of output doesn't matter, 
i.e. numbers can be printed in any order

We strongly recommend that you click here and practice it, before moving on to the solution.

One Simple Solution is to traverse all numbers from 0 to x. For every traversed number, check if it is a Jumping number. If yes, then print it. Otherwise ignore it.

C++14




#include <bits/stdc++.h>
 
using namespace std;
 
void print_sieve(int& x)
{
    int i,temp,digit;
    bool check;
     
    for(i=0;i<=x;i++)
    {
        if(i<10)
        {
            cout<<i<<" ";
            continue;
        }
        check=1;
        temp=i;
        digit=temp%10;
        temp/=10;
        while(temp)
        {
            if(abs(digit-temp%10)!=1)
            {
                check=0;
                break;
            }
            digit=temp%10;
            temp/=10;
        }
        if(check)
        cout<<i<<" ";
    }
}
 
int main()
{
    int x=105;
    print_sieve(x);
 
    return 0;
}


Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
  public static void print_sieve(int x)
  {
    int i, temp, digit;
    int check;
  
    for(i = 0; i <= x; i++)
    {
      if(i < 10)
      {
        System.out.print(i + " ");
        continue;
      }
      check = 1;
      temp = i;
      digit = temp % 10;
      temp /= 10;
      while(temp != 0)
      {
        if(Math.abs(digit - temp % 10) != 1)
        {
          check = 0;
          break;
        }
        digit = temp % 10;
        temp /= 10;
      }
      if(check != 0)
        System.out.print(i + " ");
    }
  }
  
  // Driver Code
  public static void main(String[] args)
  {
    int x = 105;
    print_sieve(x);
  }
}
 
// This code is contributed by Pushpesh Raj.


Python3




# Python3 program to implement the approach
 
# Function to print the jumping numbers
# in the range [0, x]
def print_sieve(x):
 
    # iterating over all the numbers
    # in the range [0, x]
    for i in range(x + 1):
        if(i < 10):
 
            # all numbers in [0, 9] are
            # jumping numbers
            print(i, end=" ")
            continue
 
        # the variable check tracks if
        # the number is valid
        check = 1
        temp = i
        digit = temp % 10
        temp //= 10
        while(temp > 0):
 
            if(abs(digit - temp % 10) != 1):
 
                check = 0
                break
 
            digit = temp % 10
            temp //= 10
 
        # printing i if check is 1
        if(check):
            print(i, end=" ")
 
# Driver Code
x = 105
print_sieve(x)
 
# This code is contributed by phasing17


C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
 
  static void print_sieve(int x)
  {
    int i, temp, digit;
    int check;
 
    for(i = 0; i <= x; i++)
    {
      if(i < 10)
      {
        Console.Write(i + " ");
        continue;
      }
      check = 1;
      temp = i;
      digit = temp % 10;
      temp /= 10;
      while(temp != 0)
      {
        if(Math.Abs(digit - temp % 10) != 1)
        {
          check = 0;
          break;
        }
        digit = temp % 10;
        temp /= 10;
      }
      if(check != 0)
        Console.Write(i + " ");
    }
  }
 
  // Driver Code
  public static void Main()
  {
    int x = 105;
    print_sieve(x);
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
 
function print_sieve(x)
{
    let i,temp,digit;
    let check;
     
    for(i = 0; i <= x; i++)
    {
        if(i < 10)
        {
            document.write(i," ");
            continue;
        }
        check = 1;
        temp = i;
        digit = temp % 10;
        temp = Math.floor(temp / 10);
        while(temp)
        {
            if(Math.abs(digit - temp % 10) != 1)
            {
                check = 0;
                break;
            }
            digit = temp % 10;
            temp = Math.floor(temp / 10);
        }
        if(check)
            document.write(i," ");
    }
}
 
let x = 105;
print_sieve(x);
 
// This code is contributed by shinjanpatra
 
</script>


Output

0 1 2 3 4 5 6 7 8 9 10 12 21 23 32 34 43 45 54 56 65 67 76 78 87 89 98 101 

Time Complexity: O(x)
Auxiliary Space: O(1)

An Efficient Solution can solve this problem in O(k) time where k is number of Jumping Numbers smaller than or equal to x. The idea is use BFS or DFS
Assume that we have a graph where the starting node is 0 and we need to traverse it from the start node to all the reachable nodes.

With the restrictions given in the graph about the jumping numbers, what do you think should be the restrictions defining the next transitions in the graph.

Lets take a example for input x = 90

Start node = 0
From 0, we can move to 1 2 3 4 5 6 7 8 9 
[these are not in our range so we don't add it]

Now from 1, we can move to 12 and 10 
From 2, 23 and 21
From 3, 34 and 32
.
.
.
.
.
.
and so on.

Below is BFS based implementation of above idea. 

C++




// Finds and prints all jumping numbers smaller than or
// equal to x.
#include <bits/stdc++.h>
using namespace std;
 
// Prints all jumping numbers smaller than or equal to x starting
// with 'num'. It mainly does BFS starting from 'num'.
void bfs(int x, int num)
{
    // Create a queue and enqueue 'i' to it
    queue<int> q;
    q.push(num);
 
    // Do BFS starting from i
    while (!q.empty()) {
        num = q.front();
        q.pop();
 
        if (num <= x) {
            cout << num << " ";
            int last_dig = num % 10;
 
            // If last digit is 0, append next digit only
            if (last_dig == 0)
                q.push((num * 10) + (last_dig + 1));
 
            // If last digit is 9, append previous digit only
            else if (last_dig == 9)
                q.push((num * 10) + (last_dig - 1));
 
            // If last digit is neither 0 nor 9, append both
            // previous and next digits
            else {
                q.push((num * 10) + (last_dig - 1));
                q.push((num * 10) + (last_dig + 1));
            }
        }
    }
}
 
// Prints all jumping numbers smaller than or equal to
// a positive number x
void printJumping(int x)
{
    cout << 0 << " ";
    for (int i = 1; i <= 9 && i <= x; i++)
        bfs(x, i);
}
 
// Driver program
int main()
{
    int x = 40;
    printJumping(x);
    return 0;
}


Java




// Finds and prints all jumping numbers smaller than or
// equal to x.
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG {
 
    // Prints all jumping numbers smaller than or equal to x starting
    // with 'num'. It mainly does BFS starting from 'num'.
    public void bfs(int x, int num)
    {
        // Create a queue and enqueue 'i' to it
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(num);
 
        // Do BFS starting from i
        while (!q.isEmpty()) {
            num = q.peek();
            q.poll();
            if (num <= x) {
                System.out.print(num + " ");
                int last_digit = num % 10;
 
                // If last digit is 0, append next digit only
                if (last_digit == 0) {
                    q.add((num * 10) + (last_digit + 1));
                }
 
                // If last digit is 9, append previous digit only
                else if (last_digit == 9) {
                    q.add((num * 10) + (last_digit - 1));
                }
 
                // If last digit is neither 0 nor 9, append both
                // previous and next digits
                else {
                    q.add((num * 10) + (last_digit - 1));
                    q.add((num * 10) + (last_digit + 1));
                }
            }
        }
    }
 
    // Prints all jumping numbers smaller than or equal to
    // a positive number x
    public void printJumping(int x)
    {
        System.out.print("0 ");
 
        for (int i = 1; i <= 9 && i <= x; i++) {
            this.bfs(x, i);
        }
    }
 
    // Driver program
    public static void main(String[] args) throws IOException
    {
        int x = 40;
        GFG obj = new GFG();
        obj.printJumping(x);
    }
}


Python3




# Class queue for use later
class Queue:
    def __init__(self):
        self.lst = []
 
    def is_empty(self):
        return self.lst == []
 
    def enqueue(self, elem):
        self.lst.append(elem)
 
    def dequeue(self):
        return self.lst.pop(0)
 
# Prints all jumping numbers smaller than or equal to
# x starting with 'num'. It mainly does BFS starting
# from 'num'.
def bfs(x, num):
 
    # Create a queue and enqueue i to it
    q = Queue()
    q.enqueue(num)
 
    # Do BFS starting from 1
    while (not q.is_empty()):
        num = q.dequeue()
 
        if num<= x:
            print(str(num), end =' ')
            last_dig = num % 10
 
            # If last digit is 0, append next digit only
            if last_dig == 0:
                q.enqueue((num * 10) + (last_dig + 1))
 
            # If last digit is 9, append previous digit
            # only
            elif last_dig == 9:
                q.enqueue((num * 10) + (last_dig - 1))
 
            # If last digit is neither 0 nor 9, append
            # both previous digit and next digit
            else:
                q.enqueue((num * 10) + (last_dig - 1))
                q.enqueue((num * 10) + (last_dig + 1))
 
# Prints all jumping numbers smaller than or equal to
# a positive number x
def printJumping(x):
    print (str(0), end =' ')
    for i in range(1, 10):
        bfs(x, i)
 
# Driver Program ( Change value of x as desired )
x = 40
printJumping(x)
 
# This code is contributed by Saket Modi


C#




// C# program to finds and prints all jumping
// numbers smaller than or equal to x.
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Prints all jumping numbers smaller than or
    // equal to x starting with 'num'. It mainly
    // does BFS starting from 'num'.
    public void bfs(int x, int num)
    {
        // Create a queue and enqueue 'i' to it
        Queue<int> q = new Queue<int>();
        q.Enqueue(num);
 
        // Do BFS starting from i
        while (q.Count!=0)
        {
            num = q.Peek();
            q.Dequeue();
            if (num <= x)
            {
                Console.Write(num + " ");
                int last_digit = num % 10;
 
                // If last digit is 0, append next digit only
                if (last_digit == 0)
                {
                    q.Enqueue((num * 10) + (last_digit + 1));
                }
 
                // If last digit is 9, append previous digit only
                else if (last_digit == 9)
                {
                    q.Enqueue((num * 10) + (last_digit - 1));
                }
 
                // If last digit is neither 0 nor 9, append both
                // previous and next digits
                else
                {
                    q.Enqueue((num * 10) + (last_digit - 1));
                    q.Enqueue((num * 10) + (last_digit + 1));
                }
            }
        }
    }
 
    // Prints all jumping numbers smaller than or equal to
    // a positive number x
    public void printJumping(int x)
    {
        Console.Write("0 ");
 
        for (int i = 1; i <= 9 && i <= x; i++)
        {
            this.bfs(x, i);
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int x = 40;
        GFG obj = new GFG();
        obj.printJumping(x);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
// Finds and prints all jumping numbers
// smaller than or equal to x.
 
// Prints all jumping numbers smaller than
// or equal to x starting with 'num'. It
// mainly does BFS starting from 'num'.
function bfs(x, num)
{
     
    // Create a queue and enqueue 'i' to it
    let q = [];
    q.push(num);
 
    // Do BFS starting from i
    while (q.length != 0)
    {
        num = q.shift();
         
        if (num <= x)
        {
            document.write(num + " ");
            let last_digit = num % 10;
 
            // If last digit is 0, append next digit only
            if (last_digit == 0)
            {
                q.push((num * 10) + (last_digit + 1));
            }
 
            // If last digit is 9, append previous
            // digit only
            else if (last_digit == 9)
            {
                q.push((num * 10) + (last_digit - 1));
            }
 
            // If last digit is neither 0 nor 9,
            // append both previous and next digits
            else
            {
                q.push((num * 10) + (last_digit - 1));
                q.push((num * 10) + (last_digit + 1));
            }
        }
    }
}
 
// Prints all jumping numbers smaller
// than or equal to a positive number x
function printJumping(x)
{
    document.write("0 ");
   
    for(let i = 1; i <= 9 && i <= x; i++)
    {
        bfs(x, i);
    }
}
 
// Driver code
let x = 40;
printJumping(x);
 
// This code is contributed by rag2127
 
</script>


Output

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

Time Complexity: O(k) time where k is number of Jumping Numbers smaller than or equal to x
Auxiliary Space: O(1)

Thanks to Gaurav Ahirwar for above solution.

Exercise: 

  1. Change the above solution to use DFS instead of BFS.
  2. Extend your solution to print all numbers in sorted order instead of any order.
  3. Further extend the solution to print all numbers in a given range.

DFS based solution:

In the DFS based approach we start building our numbers from single digits , i.e. from 1 – 9. Then we check for next possible digit and if possible we call the dfs for those numbers, increasing the number of digits with each call.

Algorithm:

1. We will start from every possible single digit, i.e. from 1 to 9
2. In the dfs we first write the base case, then
3. We print the current number
4. We get the last digit of current number and
  check the possibilities for the next digit.
  The next digit can either be last digit + 1 or last digit - 1 
5. If the last digit is either 0 or 9 we have only one option for 
  next number, else both the options are possible.

See C++ implementation of above approach:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
 
void dfs(ll cnum, const ll& num)
{
    if (cnum > num) // base case
        return;
 
    cout << cnum << " "; // print the current number
 
    int l_dig = cnum % 10; // get the last digit of current number
 
    // for the next digit we have two options
    ll first = cnum * 10 + l_dig + 1;
    ll second = cnum * 10 + l_dig - 1;
 
    if (l_dig == 0) // here as second option will give us a
                    // -ve number we will skip it
        dfs(first, num);
    else if (l_dig == 9) // here as first option will give
                         // us a -ve number we will skip it
        dfs(second, num);
    else // else we call on both the options
    {
        dfs(first, num);
        dfs(second, num);
    }
}
 
void PrintJumping(long long X)
{
    cout << 0 << " ";
    for (ll i = 1; i <= 9; i++) {
        dfs(i, X); // generate all the numbers starting
                   // from i
    }
}
 
int main()
{
 
    long long X = 40;
    PrintJumping(X);
    return 0;
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Java




// Java implementation of the above approach
import java.util.*;
 
class gfg2 {
    static void dfs(long cnum, long num)
    {
        if (cnum > num) // base case
            return;
 
        System.out.print(cnum
                         + " "); // print the current number
 
        int l_dig = (int)(cnum % 10); // get the last digit
                                      // of current number
 
        // for the next digit we have two options
        long first = cnum * 10 + l_dig + 1;
        long second = cnum * 10 + l_dig - 1;
 
        if (l_dig == 0) // here as second option will give
                        // us a -ve number we will skip it
            dfs(first, num);
        else if (l_dig
                 == 9) // here as first option will give
                       // us a -ve number we will skip it
            dfs(second, num);
        else // else we call on both the options
        {
            dfs(first, num);
            dfs(second, num);
        }
    }
 
    static void PrintJumping(long X)
    {
        System.out.print(0 + " ");
        for (long i = 1L; i <= 9; i++) {
            dfs(i, X); // generate all the numbers starting
                       // from i
        }
    }
    public static void main(String[] args)
    {
        long X = 40;
        PrintJumping(X);
    }
}
// This code is contributed by karandeep1234


Python3




# Python3 implementation of the above approach
def dfs(cnum, num):
    # base case
    if cnum > num:
        return
 
    # print the current number
    print(cnum, end=" ")
 
    # get the last digit of the current number
    l_dig = cnum % 10
 
    # for the next digit we have two options
    first = cnum * 10 + l_dig + 1
    second = cnum * 10 + l_dig - 1
 
    # here as second option will give us a -ve number
    # we will skip it
    if l_dig == 0:
        dfs(first, num)
    # here as first option will give us a -ve number
    # we will skip it
    elif l_dig == 9:
        dfs(second, num)
    # else we will call on both the options
    else:
        dfs(first, num)
        dfs(second, num)
 
# Print Jumping numbers
def PrintJumping(X):
    print(0, end=" ")
    for i in range(1, 10):
        dfs(i, X)
 
# Driver code
if __name__ == '__main__':
    X = 40
    PrintJumping(X)
     
    # This code is contributed by factworx412


C#




// C# implementation of the above approach
using System;
 
class GFG {
  static void dfs(long cnum, long num)
  {
    if (cnum > num) // base case
      return;
 
    Console.Write(cnum
                  + " "); // print the current number
 
    int l_dig = (int)(cnum % 10); // get the last digit
    // of current number
 
    // for the next digit we have two options
    long first = cnum * 10 + l_dig + 1;
    long second = cnum * 10 + l_dig - 1;
 
    if (l_dig == 0) // here as second option will give
      // us a -ve number we will skip it
      dfs(first, num);
    else if (l_dig
             == 9) // here as first option will give
      // us a -ve number we will skip it
      dfs(second, num);
    else // else we call on both the options
    {
      dfs(first, num);
      dfs(second, num);
    }
  }
 
  static void PrintJumping(long X)
  {
    Console.Write(0 + " ");
    for (long i = 1L; i <= 9; i++) {
      dfs(i, X); // generate all the numbers starting
      // from i
    }
  }
  static void Main(string[] args)
  {
    long X = 40;
    PrintJumping(X);
  }
}
 
// This code is contributed by karandeep1234


Javascript




// Javascript implementation of the above approach
function dfs(cnum, num)
{
    if (cnum > num) // base case
        return;
 
    console.log(cnum+" "); // print the current number
 
    let l_dig = cnum % 10; // get the last digit of current number
 
    // for the next digit we have two options
    let first = cnum * 10 + l_dig + 1;
    let second = cnum * 10 + l_dig - 1;
 
    if (l_dig == 0) // here as second option will give us a
                    // -ve number we will skip it
        dfs(first, num);
    else if (l_dig == 9) // here as first option will give
                        // us a -ve number we will skip it
        dfs(second, num);
    else // else we call on both the options
    {
        dfs(first, num);
        dfs(second, num);
    }
}
 
function PrintJumping(X)
{
    console.log(0+" ");
    for(let i = 1; i <= 9; i++) {
        dfs(i, X); // generate all the numbers starting
                // from i
    }
}
 
    let X = 40;
    PrintJumping(X);
     
// This code is contributed by Aman Kumar.


Output

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

Time Complexity: O(k)

Here k is the total number of jumping numbers.

Auxiliary Space: O(len(N))

Here len(N) is the maximum length from all the jumping numbers, the extra space is used due to recursive function call stack. 



Similar Reads

Euler's Totient function for all numbers smaller than or equal to n
Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively prime to 4, 2 numbers smaller or equal to 3 that are
13 min read
Delete Array Elements which are Smaller than Next or Become Smaller
Given an array arr[] and a number k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] &lt; arr[i+1]) or become smaller than next because next element is deleted. Example: Input : arr[] = { 3, 100, 1 }, k = 1Output : 100, 1Explanation : arr[0] &lt; arr[1] means 3 is less than 100, so delete 3 Inp
10 min read
Delete all the nodes from a doubly linked list that are smaller than a given value
Given a doubly linked list containing N nodes and a number K, the task is to delete all the nodes from the list that are smaller than the given value K. Examples: Input: 15 &lt;=&gt; 16 &lt;=&gt; 10 &lt;=&gt; 9 &lt;=&gt; 6 &lt;=&gt; 7 &lt;=&gt; 17 K = 10 Output: 15 &lt;=&gt; 16 &lt;=&gt; 10 &lt;=&gt; 17 Input: 5 &lt;=&gt; 3 &lt;=&gt; 6 &lt;=&gt; 8
13 min read
Maximize the sum of elements arr[i] selected by jumping index by value i
Given an array arr[], the task is to calculate the maximum sum of elements from the array such that, if an ith element is picked, then arr[i] is added to the sum and i jumps are taken ahead from the current index. Examples: Input: N = 5, arr[] = {7, 3, 1, 2, 3}Output: 7Explanation: Take the first element 7 to our score, then we move 7 index ahead a
6 min read
Maximize value obtained in Array by jumping to the next consecutive greater
Given an array arr[] of size N, the task is to find the maximum value that can be obtained by following the below conditions: Select any element (say k) from the array and increase all other elements by 1.In the next step, jump only to the index with a value k+1.In the end, you are at the maximum value. Examples: Input: N = 4, arr[] ={1, 2, 1, 3}Ou
6 min read
Print all positions of a given string having count of smaller characters equal on both sides
Given a string, str, the task is to find the indices of the given string such that the count of lexicographically smaller characters on the left and right sides of that index is equal and non-zero. Examples: Input: str = "aabacdabbb" Output: 2 4 Explanation: Count of smaller characters on the left side of index 2 is 2 and right side of index 2 is a
8 min read
Minimum numbers (smaller than or equal to N) with sum S
Given N numbers(1, 2, 3, ....N) and a number S. The task is to print the minimum number of numbers that sum up to give S. Examples: Input: N = 5, S = 11 Output: 3 Three numbers (smaller than or equal to N) can be any of the given combinations. (3, 4, 4) (2, 4, 5) (1, 5, 5) (3, 3, 5)Input: N = 1, S = 10 Output: 10 Approach: Greedily we choose N as m
3 min read
Sieve of Sundaram to print all primes smaller than n
Given a number n, print all primes smaller than or equal to n. Examples: Input: n = 10 Output: 2, 3, 5, 7 Input: n = 20 Output: 2, 3, 5, 7, 11, 13, 17, 19 We have discussed Sieve of Eratosthenes algorithm for the above task. Below is Sieve of Sundaram algorithm. printPrimes(n) [Prints all prime numbers smaller than n] 1) In general Sieve of Sundara
10 min read
C++ Program to Count triplets with sum smaller than a given value
Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input : arr[] = {5, 1, 3, 4, 7} sum = 12. Output : 4 Expl
4 min read
Java Program to Count triplets with sum smaller than a given value
Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples:   Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input : arr[] = {5, 1, 3, 4, 7} sum = 12. Output : 4 Ex
4 min read