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:
- Smallest number greater than Y with sum of digits equal to X
- Smallest number greater than or equal to X whose sum of digits is divisible by Y
- Smallest number greater than or equal to N divisible by K
- Smallest Special Prime which is greater than or equal to a given number
- Smallest number k such that the product of digits of k is equal to n
- Smallest power of 4 greater than or equal to N
- Highest and Smallest power of K less than and greater than equal to N respectively
- Smallest subarray from a given Array with sum greater than or equal to K
- Find smallest number with given number of digits and sum of digits under given constraints
- Smallest number with given sum of digits and sum of square of digits
- Find smallest number with given number of digits and sum of digits
- Find next greater number with same set of digits
- Largest number not greater than N all the digits of which are odd
- Next greater Number than N with the same quantity of digits A and B
- Smallest number greater or equals to N such that it has no odd positioned bit set
- Next greater number on the basis of precedence of digits
- Nearest greater number by interchanging the digits
- Smallest number greater than n that can be represented as a sum of distinct power of k
- Smallest even digits number not less than N
- Smallest odd number with N digits
Improved By : himanshu77