![]() |
VOOZH | about |
A number is called a Jumping Number if all adjacent digits differ by 1.
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
Table of Content
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.
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
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.
0 1 10 12 2 21 23 3 32 34 4 5 6 7 8 9
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.
0 1 12 10 2 23 21 3 34 32 4 5 6 7 8 9