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 C++ 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
- Find the Largest number with given number of digits and sum of digits
- Find smallest number with given number of digits and sum of digits
- Find count of digits in a number that divide the number
- Print a number strictly less than a given number such that all its digits are distinct.
- Number of digits to be removed to make a number divisible by 3
- Find the smallest number whose digits multiply to a given number n
- Number of times a number can be replaced by the sum of its digits until it only contains one digit
- Find maximum number that can be formed using digits of a given number
- Count number of digits after decimal on dividing a number
- Number of digits in the nth number made of given four digits
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Maximize the given number by replacing a segment of digits with the alternate digits given
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Check if a number with even number of digits is palindrome or not
- Round-off a number to a given number of significant digits