402: Solution with step by step explanation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThe algorithm uses a stack to keep track of the digits. It loops through 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe algorithm uses a stack to keep track of the digits. It loops through each digit in num, and for each digit, it pops digits from the stack until either the top digit is smaller than the current digit or k becomes 0. Then it appends the current digit to the stack. After looping through all digits in num, if there are still digits to be removed (i.e., k > 0), it pops digits from the stack until k becomes 0.\n\nFinally, it converts the remaining digits in the stack to a string and removes any leading zeroes, then returns the resulting string. If there are no remaining digits, it returns the string "0".\n\nOverall, the algorithm has a time complexity of O(n), where n is the length of num, and a space complexity of O(n), as the stack can store up to all n digits of num.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n    def removeKdigits(self, num: str, k: int) -> str:\n        stack = []  # Use a stack to keep track of the digits\n        for digit in num:\n            while k > 0 and stack and stack[-1] > digit:  # Pop digits from the stack until the top digit is smaller than the current digit or k becomes 0\n                stack.pop()\n                k -= 1\n            stack.append(digit)  # Append the current digit to the stack\n        while k > 0:  # If there are still digits to be removed, pop them from the stack\n            stack.pop()\n            k -= 1\n        result = "".join(stack).lstrip("0")  # Convert the remaining digits to a string and remove any leading zeroes\n        return result if result else "0"  # Return the resulting string, or "0" if there are no remaining digits\n\n```
['String', 'Stack', 'Greedy', 'Python', 'Python3']