Finding the Nth term in a sequence formed by removing digit K from natural numbers
Given the integers N, K and an infinite sequence of natural numbers where all the numbers containing the digit K (1<=K<=9) are removed. The task is to return the Nth number of this sequence.
Input: N = 12, K = 2
Explanation: The sequence generated for the above input would be like this: 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, up to infinity
Input: N = 10, K = 1
Naive Approach: The basic approach to solving the above problem would be to iterate up to N and keep excluding all numbers less than N containing the given digit K. Finally, print the Nth natural number obtained.
- Initialize count to 0 and i to 1
- While count is less than n:
- Check if i contains the digit k by calling the containsDigit function
- If i does not contain k:
- Increment count by 1
- If count is equal to n:
- Return i as the nth natural number that does not contain k.
- Otherwise, increment i by 1 and continue to the next iteration of the loop
- If we have iterated up to N without finding the nth natural number that does not contain k, return -1 (this is an error condition)
- containsDigit function:
- Initialize a variable called numCopy to the value of num
- While numCopy is greater than 0:
- Check if the last digit of numCopy is equal to k
- If it is, return true
- Otherwise, divide numCopy by 10 to remove the last digit.
- If we have checked all the digits in num and have not found k, return false.
The 12th natural number not containing 2 is: 14
Time Complexity: O(N*d), where N is the input value and d is the number of digits in N.
Auxiliary Space: O(1)
Efficient Approach: The efficient approach to solve this is inspired by the Nth natural number after removing all numbers consisting of the digit 9.
The given problem can be solved by converting the value of K to base 9 forms if it is more than 8. Below steps can be followed:
- Calculate the Nth natural number to base 9 format
- Increment 1 to every digit of the base 9 number which is greater than or equal to K
- The next number is the desired answer
Below is the code for the above approach:
Time Complexity: O(log9N)
Auxiliary Space: O(1)
Please Login to comment...