Given a number N, the task is to find the Nth number which has an absolute difference of 1 between every pair of its adjacent digits.
Input : N = 5
Output : 5
The first 5 such numbers are 1,2,3,4 and 5.
Input : N = 15
Output : 23
The first 15 such numbers are 1,2,3,4,5,6,7,8,9,10,11,12,21,22 and 23.
Approach: In order to solve this problem we are using the Queue data structure.
- Prepare an empty Queue, and Enqueue all integers 1 to 9 in increasing order.
- Now perform the following operation N times.
- Dequeue and store in array arr which stores ith number of required type in arr[i].
- If (arr[i] % 10 != 0), then enqueue 10 * arr[i] + (arr[i] % 10) – 1.
- Enqueue 10 * arr[i] + (arr[i] % 10).
- If (arr[i] % 10 != 9), then enqueue 10 * arr[i] + (arr[i] % 10) + 1.
- Return arr[N] as the answer.
Below is the implementation of the given approach:
- Count of numbers upto N having absolute difference of at most K between any two adjacent digits
- Find Nth positive number whose digital root is X
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K
- Count of N-digit numbers with absolute difference of adjacent digits not exceeding K | Set 2
- Generate all N digit numbers having absolute difference as K between adjacent digits
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Number of digits in the nth number made of given four digits
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Maximize absolute difference between X and Y by at most N decrements
- Count of numbers upto N digits formed using digits 0 to K-1 without any adjacent 0s
- Sort an Array based on the absolute difference of adjacent elements
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Maximise sum of absolute difference between adjacent elements in Array with sum K
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Minimize the maximum difference of adjacent elements after at most K insertions
- Minimize positive product of two given numbers by at most N decrements
- Pair with min absolute difference and whose product is N+1 or N+2
- Count of elements whose absolute difference with the sum of all the other elements is greater than k
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.