
Sponsored
Sponsored
This approach uses a stack to build the smallest possible number. We iterate over each digit in the string, and for each digit, we compare it with the top of the stack (if the stack is not empty). If the current digit is smaller than the top of the stack and we still have digits to remove, we pop from the stack. Finally, after the loop, if there are remaining digits to remove, we simply remove them from the end of the constructed stack. This ensures the smallest possible arrangement of the remaining digits.
Time Complexity: O(n), where n is the number of digits in num, because each digit is processed at most twice (once pushed and once popped).
Space Complexity: O(n), because of the space required for the stack to hold the digits.
1def removeKdigits(num: str, k: int) -> str:
2 stack = []
3 for digit in num:
4 while k > 0 and stack and stack[-1] > digit:
5 stack.pop()
6 k -= 1
7 stack.append(digit)
8 # If k still > 0, remove the remaining digits from the end
9 final_stack = stack[:-k] if k else stack
10 # Convert to string and remove leading zeros
11 return ''.join(final_stack).lstrip('0') or '0'This Python implementation utilizes a stack to keep track of the most desirable sequence of digits. As the function iterates over each digit, it determines whether the stack should pop any elements based on whether doing so would create a smaller number. After the loop, any remaining digits are removed by slicing off the end of the stack. Leading zeros are removed from the final result, and if this leads to an empty string, we return '0'.