🟢Beats 100.00% of users with Java, Best Solution with Explanation
Keep growing \uD83D\uDE0A\n\n\n---\n\n# Complexity\n\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n---\n\n# Approach Explanation\n\n1. Boundary Check:
##### Keep growing \uD83D\uDE0A\n![image.png](https://assets.leetcode.com/users/images/0e7fb747-088d-45c3-b109-263439084113_1712804891.0137038.png)\n\n---\n\n# Complexity\n\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n---\n\n# Approach Explanation\n\n1. **Boundary Check**: Checks if `k` equals the length of `num`. If true, returns "0".\n\n2. **Using a Stack**: Utilizes a stack to track digits and their order.\n\n3. **Iterating Through Digits**: Iterates through each digit in `num`.\n\n4. **Removing Larger Digits**: While `removalCount > 0` and the current digit is smaller than the top of the stack, removes digits from the stack.\n\n5. **Building the Stack**: Adds current digits to the stack after removing larger ones.\n\n6. **Truncating Leading Zeros**: Determines the starting index of non-zero digits to form the smallest possible number.\n\n7. **Returning Result**: Constructs and returns the result string, excluding leading zeros.\n---\n\n# Code\n\n```java []\nclass Solution {\n    public static String removeKdigits(String num, int k) {\n        if (k == num.length()) {\n            return "0";\n        }\n\n        char[] digits = num.toCharArray();\n        char[] stack = new char[digits.length];\n        int stackTop = -1;\n        int removalCount = k;\n\n        for (int i = 0; i < digits.length; i++) {\n            while (removalCount > 0 && stackTop >= 0 && stack[stackTop] > digits[i]) {\n                stackTop--;\n                removalCount--;\n            }\n            stackTop++;\n            stack[stackTop] = digits[i];\n        }\n\n        int nonZeroStart = 0;\n\n        while (stack[nonZeroStart] == \'0\' && nonZeroStart < digits.length - k - 1) {\n            nonZeroStart++;\n        }\n\n        return String.valueOf(stack, nonZeroStart, digits.length - k - nonZeroStart);\n    }\n}\n```\n----\n\n# *If you have any question, feel free to ask. If you found my solution helpful, Please UPVOTE !* \uD83D\uDE0A
['String', 'Stack', 'Greedy', 'Monotonic Stack', 'Java']