Intermediate Level

Implement the removeKDigitsMinimum method that removes k digits to form the smallest possible number.

The input contains a numeric string number and an integer k. Your task is to remove exactly k digits from the string so that the remaining number is as small as possible.

The relative order of the remaining digits must stay the same. Leading zeroes should be removed from the final result.

If all digits are removed, or the remaining value becomes empty after removing leading zeroes, return 0.

Example 1
Input:
number (string) = 1432219
k (int) = 3
Return:
(string) "1219"
Example 2
Input:
number (string) = 10200
k (int) = 1
Return:
(string) 200
Example 3
Input:
number (string) = 10
k (int) = 2
Return:
(string) 0

Use a greedy monotonic stack.

While scanning the digits, remove a previous digit if it is larger than the current digit and removals are still available. This makes the earlier part of the number smaller, which gives the smallest possible final value.

After scanning all digits, if some removals are still left, remove digits from the end. Finally, remove leading zeroes and return 0 if the result is empty.

Pseudocode:

function removeKDigitsMinimum(number, k):
    stack = empty stack
    for each digit in number:
        while k > 0 and stack is not empty and top(stack) > digit:
            pop stack
            k--
        push digit into stack
    while k > 0 and stack is not empty:
        pop stack
        k--
    result = join stack values
    remove leading zeroes from result
    if result is empty:
        return "0"
    return result
Run your code to see the result.