VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-jumping-numbers-smaller-than-or-equal-to-a-given-value/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

A number is called a Jumping Number if all adjacent digits differ by 1.

  • The difference between ‘9’ and ‘0’ is not considered 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

[Naive Approach] Traversing and Checking All Numbers - O(x) Time and O(1) Space

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.


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 

[Expected Approach] Using BFS - O(k) Time and O(k) Space

The approach uses Breadth-First Search (BFS) to generate Jumping Numbers starting from digits 1 to 9. Each number expands by appending its last digit ±1 (if valid), ensuring adjacent digits differ by 1. The process continues until numbers exceed x, taking O(k) time and space, where k is the count of valid Jumping Numbers less than or equal to x.


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

[Alternate Approach] using DFS - O(k) Time and O(k) Space

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. The process continues until numbers exceed x, taking O(k) time and space, where k is the count of valid Jumping Numbers less than or equal to x.


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


Comment