Given a string ‘str’ of digits and an integer ‘n’, build the lowest possible number by removing ‘n’ digits from the string and not changing the order of input digits.
Input: str = "4325043", n = 3 Output: "2043" Input: str = "765028321", n = 5 Output: "0221" Input: str = "121198", n = 2 Output: "1118"
The idea is based on the fact that a character among first (n+1) characters must be there in resultant number. So we pick the smallest of first (n+1) digits and put it in result, and recur for remaining characters. Below is complete algorithm.
Initialize result as empty string res = "" buildLowestNumber(str, n, res) 1) If n == 0, then there is nothing to remove. Append the whole 'str' to 'res' and return 2) Let 'len' be length of 'str'. If 'len' is smaller or equal to n, then everything can be removed Append nothing to 'res' and return 3) Find the smallest character among first (n+1) characters of 'str'. Let the index of smallest character be minIndex. Append 'str[minIndex]' to 'res' and recur for substring after minIndex and for n = n-minIndex buildLowestNumber(str[minIndex+1..len-1], n-minIndex).
Below is the implementation of above algorithm.
Below is an optimised code in C++ contributed by Gaurav Mamgain
Time Complexity: O(n)
Space Complexity: O(n)
This article is contributed by Pallav Gurha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Reduce the number to minimum multiple of 4 after removing the digits
- Find smallest number with given number of digits and sum of digits under given constraints
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Find smallest number with given number of digits and sum of digits
- Find the Largest number with given number of digits and sum of digits
- Number formed by deleting digits such that sum of the digits becomes even and the number odd
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Find smallest possible Number from a given large Number with same count of digits
- Find the smallest number whose digits multiply to a given number n
- Number of digits to be removed to make a number divisible by 3
- Number of times a number can be replaced by the sum of its digits until it only contains one digit
- Count number of digits after decimal on dividing a number
- Print a number strictly less than a given number such that all its digits are distinct.
- Find maximum number that can be formed using digits of a given number
- Find count of digits in a number that divide the number