Remove k digits

Remove k digits from a number to leave the smallest possible result, using a monotonic increasing stack of digits.

Time O(n)Space O(n)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A number is smaller when its leftmost differing digit is smaller. So whenever the next digit is smaller than the one on top of the stack, popping that bigger digit (if there is still a removal to spend) always helps, or at worst does not hurt. Any removals left over once every digit has been read are spent trimming the largest, right-most digits that remain.

Code

public static string RemoveKdigits(string num, int k) {
    var stack = new Stack<char>();
    foreach (char d in num) {
        while (k > 0 && stack.Count > 0 && stack.Peek() > d) {
            stack.Pop(); k--;
        }
        stack.Push(d);
    }
    while (k-- > 0) stack.Pop();
    var digits = stack.Reverse().SkipWhile(c => c == '0').ToArray();
    return digits.Length == 0 ? "0" : new string(digits);
}

Tips

In the .NET library

stack.Reverse() walks a Stack<char> from top to bottom, which here is also left to right, since digits were pushed in reading order with only the top ever popped.