Given the string representation of a non-negative integer and an integer k, find the smallest number that remains after taking out k digits from it. Assume that the string contains atleast k digits.

For example,

Input: str = 284729, k = 2
Output: 2429
Explanation: We can obtain the smallest number, 2429, by removing two digits (8 and 7) from 284729.
 
Input: str = 101, k = 1
Output: 1
Explanation: Remove the first one to form the smallest number 1.

There is a simple rule to get the smallest number possible by removing a single digit from it: process the digits from left to right and remove the first digit that is greater than its subsequent digit. We can easily extend this solution for k digits by repeating this process k times. However, the time complexity of this approach is O(n2).

 
We can reduce the time complexity to linear by using the stack to store the possible candidates up until the present position. The idea is to iterate over the string from left to right and maintain a stack data structure. If the current digit is less than the top digit of the stack, repeatedly remove digits from the stack until the current digit becomes greater than the top element. Then push the current digit to the stack only if it doesn’t result in any leading zeros. Once the k pop operations on the stack have been completed, insert the remaining digits into the stack. If k pop operations have not been done on the stack at the end of the iteration, remove the excess digits from the top of the stack. Finally, construct a new string from the stack’s elements, from bottom to top.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

2429

Java


Download  Run Code

Output:

2429

Python


Download  Run Code

Output:

2429

The time complexity of the above solution is O(n) and requires O(n) additional space for the stack data structure, where n is the number of digits.