Problem Description
Given a string representing a non-negative integer and an integer k, remove k digits from the string such that the resulting number is the smallest possible. The output should not contain any unnecessary leading zeros; if the number is reduced to nothing, return "0".
Key Insights
- Use a greedy approach that removes digits to make the number as small as possible.
- Utilize a stack (monotonic increasing sequence) to decide whether to keep or remove a digit.
- Remove any excess digits from the end if k > 0 after the primary loop.
- Handle edge cases including leading zeros and the possibility of removing all digits.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), needed for the stack.
Solution
We apply a greedy algorithm using a monotonic stack. For each digit in the number, if the current digit is smaller than the last digit on the stack and we still have removals (k > 0), we pop from the stack. This removal helps in making the constructed number smaller. After iterating over the entire number, if any removals remain, we trim the number from the end. Finally, we join the resulting digits, strip leading zeros, and if the result is empty, we return "0".