Given a number N and an integer K, the task is to find the smallest number greater than or equal to N, formed using only first K non-zero digits( 1, 2, …, K-1, K).
Input: N = 124, K = 3
The smallest number greater than or equal to 124, which is only made of digits 1, 2, 3 is 131.
Input: N = 325242, K = 4
The simplest solution is to start a for loop from N + 1 and find the first number made up of first K digits.
To obtain an efficient solution, we need to understand the fact that a maximum of 9 digit number can be formed up-to 1010. So, we will iterate over digits of the number in reverse and check:
- If current digit >= K then, make that digit = 1.
- If current digit < K and there is no digit greater than K after this, then increment the digit by 1 and copy all the remaining digits as it is.
- Once we have iterated over all the digits and still haven’t found any digit which is less than K then we need to add a digit (1) to the answer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.