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
- Count of integers in a range which have even number of odd digits and odd number of even digits
- 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 the number of positive integers less than or equal to N that have an odd number of digits
- Find maximum number that can be formed using digits of a given number
- Number of times a number can be replaced by the sum of its digits until it only contains one digit
- Number of digits to be removed to make a number divisible by 3
- 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.
- Find the smallest number whose digits multiply to a given number n
- 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
- Sum and Product of digits in a number that divide the number