Given a string S consisting of digits from 0 to 9 inclusive, the task is to form the lexicographically smallest string by performing an operation any number of times. In one operation you can choose any position i and delete the digit d at s[i] and insertmin(d+1, 9) on any position (at the beginning, at the end, or in between any two adjacent digits).
Input: s = “04829” Output: “02599” Explanation: Delete 8 and insert 9 at the end of the string, the resulting string is 04299 then delete 4 and insert 5 in the 2nd position of the string. The resulting string is 02599.
Input: s = “07” Output: “07” Explanation: Nothing needs to be done here. It is already the lexicographically smallest string we can get.
Approach: To solve the problem follow the below idea:
The idea is to place the smallest digit just before the greater digit in order to form the lexicographically Smallest string. This can be done by iterating from second last digit and if any digit d is found to be greater than its next digit, delete it and insert min (d+1, 9) to the position such that it is smaller than its next digit and greater than its previous digit i.e., string remains in increasing order. We can use priority queue to place the digit to its correct position.
Follow the steps mentioned below to implement the idea:
Declare the min heap which stores the digit at its correct position.
Iterate from the second last digit in the reverse direction and if the current digit is found greater than the digit at its next index, delete it
Insert min (d+1, 9) in the priority queue (min-heap)
Declare the new string ans to store the resultant string.
Pop out the top digit from the priority queue until the queue becomes empty and insert it into the resultant string.
Return the resultant string formed.
Below is the implementation of the above approach:
Please Login to comment...