vector/list as monotonic stack||2ms Beats 99.62%
Intuition\n Describe your first thoughts on how to solve this problem. \nUse monotonic stack. C++ vector/Python list has all similar methods like stack. So, use
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse monotonic stack. C++ vector/Python list has all similar methods like stack. So, use vector/list.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. set `vector<char> st` as monotonic stack\n2. transverse the string `num` for each iteration `c` in `num` do the following\n```\nwhile(!st.empty() && c<st.back() && k>0){\n    k--;\n    st.pop_back();\n}\nst.push_back(c); \n```\n3. Remove characters if k>0\n4. Removing leading \'0\'s\n5. return ` ans`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code 2ms Beats 99.62%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n    string removeKdigits(string& num, int k) {\n        int n=num.size();\n        if (n==k) return "0";\n        vector<char> st;\n        for(char c: num){// monotonic stack\n            while(!st.empty() && c<st.back() && k>0){\n                k--;\n                st.pop_back();\n             }\n            st.push_back(c);            \n        }\n        while(k>0){\n           st.pop_back();\n            k--;\n        }\n        int j=0, m=st.size();\n        while(st[j]==\'0\'&& j<m-1) j++;// Removing leading \'0\'s\n        string ans(st.begin()+j, st.end());\n        return ans==""?"0":ans;\n    }\n};\n\n\nauto init = []() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    return \'c\';\n}();\n```\n# Python version\n```\nclass Solution:\n    def removeKdigits(self, num: str, k: int) -> str:\n        n=len(num)\n        if n==k: return "0"\n        st=[]\n        for c in num:\n            while st and c<st[-1] and k>0:\n                k-=1\n                st.pop()\n            st.append(c)\n    #    print(st)\n        while k>0:\n            st.pop()\n            k-=1\n        j=0\n        m=len(st)\n        while st[j]==\'0\' and j<m-1:\n            j+=1\n        if j==n-1 or st==None: return "0"\n        return \'\'.join(st[j:])\n\n        \n```
['Monotonic Stack', 'C++', 'Python3']