C++ Remove K Digits: line-by-line walkthrough
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\nk\nclass Solution {\n   public:\n    string removeKdigits(string num, int k) {\n   
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```k\nclass Solution {\n   public:\n    string removeKdigits(string num, int k) {\n        // Initialize a stack to store the digits\n        stack<char> stk;\n        // Iterate through the digits of the input string\n        for (char c : num) {\n            // While there are still digits to remove and the top of the stack is larger than the current digit\n            while (k > 0 && !stk.empty() && stk.top() > c) {\n                // Pop the top element from the stack\n                stk.pop();\n                // Decrement the counter\n                k--;\n            }\n            // Push the current digit onto the stack\n            stk.push(c);\n        }\n        // While there are still digits to remove\n        while (k > 0) {\n            // Pop the top element from the stack\n            stk.pop();\n            // Decrement the counter\n            k--;\n        }\n        // Initialize a string to store the result\n        string res;\n        // While the stack is not empty\n        while (!stk.empty()) {\n            // Append the top element of the stack to the result string\n            res += stk.top();\n            // Pop the top element from the stack\n            stk.pop();\n        }\n        // Reverse the result string\n        reverse(res.begin(), res.end());\n        // Remove leading zeros\n        while (res.size() > 1 && res[0] == \'0\') {\n            res.erase(res.begin());\n        }\n        // If the result string is empty, return "0"\n        if (res.empty()) {\n            return "0";\n        }\n        // Return the result string\n        return res;\n    }\n};\n```
['Stack', 'C++']