Full Explained Intuitive Solution || [Java/C++/Python3]
Intuition\n##### To solve this problem, we use a stack. First, we push the first element of the number into the stack, making sure it\'s not a zero. Then, as we
# Intuition\n##### ***To solve this problem, we use a stack. First, we push the first element of the number into the stack, making sure it\'s not a zero. Then, as we encounter the next elements, we compare them with the top element of the stack. If the new element is smaller, it has the potential to create a smaller number. So, we pop the top element from the stack and push the new element instead. But we need to be careful about how many elements we pop from the stack because we can only delete up to k digits.***\n```\nnum = "1432219", k = 3\nwe first push 1 into the stack\n           |         |\n           |         |\n           |         |   <-----Stack representation\n           |   1     |\n           |_________|\n\nnow we encounter 4 we check if 4 is lesser than 1 as it is not we push into the stack.\n\n           |         |\n           |         |\n           |         |   <-----Stack representation\n           |   4     |\n           |___1_____|\n\nthen 3 comes as it is lesser than the top of the stack we pop 4 out and we push 3 in while simultaneously decrementing k . \n\n           |         |\n           |         |\n           |         |   <-----Stack representation  k=2\n           |   3     |\n           |___1_____|\n\n2 beats 3 so 3 is popped out and 2 is pushed and k is decremented.\n\n           |         |\n           |         |\n           |         |   <-----Stack representation  k=1\n           |   2     |\n           |___1_____|\n2 doesnt beat 2 so it is pushed into the stack\n\n           |         |\n           |         |\n           |   2     |   <-----Stack representation\n           |   2     |\n           |___1_____|\n1 beats 2 so 2 is popped out and 1 is pushed in.\n\n           |         |\n           |         |\n           |   1     |   <-----Stack representation   k=0\n           |   2     |\n           |___1_____|    \nnow we have the push whatever number is left as we have used up all our deletions\n\n           |         |\n           |   9     |\n           |   1     |   <-----Stack representation\n           |   2     |\n           |___1_____|\n\n           answer:-1219.\n\nWe will take another example to make sure our algorithm doesnt have leading 0s.\n\nnum = "10200", k = 1\n\n           |         |\n           |         |\n           |         |   <-----Stack representation\n           |   1     |\n           |_________|\n0 beats 1 but we should push 0 as this will cause leading zeros so we push the element if(ans.size()||c!=\'0\') meaning\nif ans.size()==0 and c==\'0\' it wouldnt push.\n\nbut we wedelete 1 as we have to fulfil the condition of the number of deleteions.\n\n           |         |\n           |         |\n           |         |   <-----Stack representation   k=0\n           |   2     |\n           |_________|\n\n           push  rest of the elements by making use of if(ans.size()||c!=\'0\')push(element).\n\n\n\n           |         |\n           |   0     |\n           |   0     |   <-----Stack representation   k=0\n           |   2     |\n           |_________|\n\n\n           answer is 200\n```\n\n# Approach\n1. **Boundary Case Check**: If the number of digits to be removed (`k`) is equal to the length of the number (`n`), then the entire number is removed, and the result would be "0".\n   \n2. **Using a Stack**:\n   - We use a stack to keep track of the digits. We iterate through each digit of the number:\n     - While the stack is not empty, `k` is greater than 0, and the top element of the stack is greater than the current digit, we pop elements from the stack and decrement `k`. This operation ensures that we remove larger digits that would contribute to a larger number.\n     - After this operation, we push the current digit onto the stack.\n   \n3. **Removing Remaining Digits**: If there are still digits to be removed (`k` > 0) after the above step, we pop elements from the stack until `k` becomes 0.\n   \n4. **Constructing the Result**: We construct the result by popping digits from the stack and appending them to a StringBuilder. Since we need to output the smallest number, we reverse the StringBuilder to maintain the correct order of digits.\n   \n5. **Removing Trailing Zeroes**: We remove any leading zeroes from the result, except if the result is "0".\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n    public String removeKdigits(String num, int k) {\n        int n = num.length();\n        if(k==n) {\n            return "0";\n        }\n\n        Stack<Character> st = new Stack<>();\n\n        for(int i=0; i<n; i++) {\n            char digit = num.charAt(i);\n            while(!st.isEmpty() && k > 0 && st.peek() > digit) {\n                st.pop();\n                k--;\n            }\n            st.push(digit);\n        }\n\n\n        while(k > 0) {\n            st.pop();\n            k--;\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while(!st.isEmpty()) {\n            sb.append(st.pop());\n        }\n        sb.reverse();\n        while(sb.length() > 1 && sb.charAt(0)==\'0\') {\n            sb.deleteCharAt(0);\n        }\n        return sb.toString();\n    }\n}\n```\n```C++ []\nclass Solution {\npublic:\n    string removeKdigits(string num, int k) {\n        int n = num.length();\n        if (k == n) {\n            return "0";\n        }\n\n        stack<char> st;\n\n        for (int i = 0; i < n; i++) {\n            char digit = num[i];\n            while (!st.empty() && k > 0 && st.top() > digit) {\n                st.pop();\n                k--;\n            }\n            st.push(digit);\n        }\n\n        while (k > 0) {\n            st.pop();\n            k--;\n        }\n\n        string result = "";\n        while (!st.empty()) {\n            result = st.top() + result;\n            st.pop();\n        }\n\n        // Removing leading zeroes\n        while (result.length() > 1 && result[0] == \'0\') {\n            result.erase(0, 1);\n        }\n\n        return result;\n    }\n};\n```\n```Python3 []\nclass Solution:\n    def removeKdigits(self, num: str, k: int) -> str:\n        n = len(num)\n        if k == n:\n            return "0"\n\n        st = []\n        for digit in num:\n            while st and k > 0 and st[-1] > digit:\n                st.pop()\n                k -= 1\n            st.append(digit)\n\n        while k > 0:\n            st.pop()\n            k -= 1\n\n        result = \'\'.join(st).lstrip(\'0\')\n\n        return result if result else "0"\n```\n```Go []\nfunc (s Solution) removeKdigits(num string, k int) string {\n\tn := len(num)\n\tif k == n {\n\t\treturn "0"\n\t}\n\n\tvar st []byte\n\n\tfor i := 0; i < n; i++ {\n\t\tdigit := num[i]\n\t\tfor len(st) > 0 && k > 0 && st[len(st)-1] > digit {\n\t\t\tst = st[:len(st)-1]\n\t\t\tk--\n\t\t}\n\t\tst = append(st, digit)\n\t}\n\n\tfor k > 0 {\n\t\tst = st[:len(st)-1]\n\t\tk--\n\t}\n\n\tresult := strings.TrimLeft(string(st), "0")\n\n\tif result == "" {\n\t\treturn "0"\n\t}\n\treturn result\n}\n```\n```C# []\npublic class Solution {\n    public string RemoveKdigits(string num, int k) {\n        int n = num.Length;\n        if (k == n) {\n            return "0";\n        }\n\n        Stack<char> st = new Stack<char>();\n\n        for (int i = 0; i < n; i++) {\n            char digit = num[i];\n            while (st.Count > 0 && k > 0 && st.Peek() > digit) {\n                st.Pop();\n                k--;\n            }\n            st.Push(digit);\n        }\n\n        while (k > 0) {\n            st.Pop();\n            k--;\n        }\n\n        StringBuilder sb = new StringBuilder();\n        while (st.Count > 0) {\n            sb.Insert(0, st.Pop());\n        }\n        sb.Replace("0", "").ToString();\n\n        return sb.Length == 0 ? "0" : sb.ToString();\n    }\n}\n```\n```JavaScript []\n/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nvar removeKdigits = function(num, k) {\n    const n = num.length;\n    if (k === n) {\n        return "0";\n    }\n\n    const stack = [];\n\n    for (let i = 0; i < n; i++) {\n        const digit = num.charAt(i);\n        while (stack.length > 0 && k > 0 && stack[stack.length - 1] > digit) {\n            stack.pop();\n            k--;\n        }\n        stack.push(digit);\n    }\n\n    while (k > 0) {\n        stack.pop();\n        k--;\n    }\n\n    let result = stack.join(\'\').replace(/^0+/, \'\');\n\n    return result === \'\' ? "0" : result;\n};\n```\n\n---\n\n\n---\n\n![5c63d377-8ef4-4beb-b09d-0edb07e09a41_1702955205.6568592.png](https://assets.leetcode.com/users/images/2fc9cc1d-0c42-41d5-8042-2daff0846a74_1712846898.406845.png)\n\n
['Stack', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']