✅Easy✨||C++|| Beats 100% || With Explanation ||
Intuition\n Describe your first thoughts on how to solve this problem. \nTo find the smallest possible integer after removing k digits from the given number, we
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find the smallest possible integer after removing k digits from the given number, we need to ensure that the remaining digits form the smallest number. We may achieve this by iteratively removing digits that are greater than the following digit.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. If the length of the input number is equal to k, then we simply return "0" because removing all digits would result in a zero.\n2. We use a stack to keep track of the digits as we iterate through the input number.\nF3. or each digit, while there are still digits to remove (k > 0), and the current digit is smaller than the digit at the top of the stack, we pop the digit from the stack and decrement k.\n4. After processing all digits, if there are still digits to remove (k > 0), we continue popping digits from the stack until k becomes zero.\n5. Finally, we construct the result string by appending digits from the stack to form the smallest possible number, ignoring leading zeros.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the solution is O(n), where n is the length of the input string num. This is because we iterate through each character in the input string once.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is also O(n), where n is the length of the input string num. This is because we use a stack to store at most all characters from the input string. Additionally, the space used by the output string ans also depends on the length of num.\n# Code\n```\nclass Solution {\n public:\n  string removeKdigits(string num, int k) {\n    if (num.length() == k)\n      return "0";\n\n    string ans;\n    vector<char> stack;\n\n    for (int i = 0; i < num.length(); ++i) {\n      while (k > 0 && !stack.empty() && stack.back() > num[i]) {\n        stack.pop_back();\n        --k;\n      }\n      stack.push_back(num[i]);\n    }\n\n    while (k-- > 0)\n      stack.pop_back();\n\n    for (const char c : stack) {\n      if (c == \'0\' && ans.empty())\n        continue;\n      ans += c;\n    }\n\n    return ans.empty() ? "0" : ans;\n  }\n};\n```
['C++']