Python using stack O(n) with explain
This question is very similar to 316. Remove Duplicate Letters with little bit extra work\n\nthe way to make number as small as possible is that make right most
This question is very similar to [316. Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/description/) with little bit extra work\n\nthe way to make number as small as possible is that make right most digit as small as possible\n\nthen come back to question, we know we can remove at most k digit to generate new digit\nso we can add/remove until k == 0\n\nas example of "1432219"\n[]\n['1']           => since stack is empty , just add into stack\n['1', '4']     => since 1 < 4, so we do not need to repalce \n['1', '3']     => since 3 is less than 4, andwe have k(3)-- times able to remove,so we can \n                      replace 4 with 3\n['1', '2']     => 2 < 3, replace 3 with 2 k(2) --\n['1', '2', '2']     => 2 == 2, continue\n['1', '2', '1']     => since 1 < 2, replace it k(1)--\n['1', '2', '1', '9']  => does not matter the next number is less or greater, since k is zero, we \n                               can not remove any more digit, so this is the end of program\n\nsome case need to handle is avoid leading zero, which seems like the only different to [316. Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/description/)\n\n```python\n    def removeKdigits(self, num, k):\n        """\n        :type num: str\n        :type k: int\n        :rtype: str\n        """\n        stack = []\n        for i in range(len(num)):\n            \n            while True:\n                if  k == 0 or not stack:\n                    break\n                \n                if stack[-1] > num[i]:\n                    k -= 1\n                    stack.pop()\n                else:\n                    break\n            stack.append(num[i])\n        while k != 0:\n            stack.pop()\n            k -= 1\n        for i in range(len(stack)):\n            if stack[i] != "0":\n                break\n        stack = stack[i:]\n\n        if not stack:\n            return "0"\n        return "".join(stack)\n```
[]