Problem Description
Given a string s containing only lowercase English letters and digits, repeatedly perform the following operation: find the first digit in the string and delete that digit together with its closest non-digit character to its left. Continue performing these operations until there are no digits left in s. Return the resulting string. Note that the operation cannot be applied if there is no non-digit character to the left of a digit. The input is generated such that it is always possible to delete all digits.
Key Insights
- We need to simulate an operation that removes a digit and its adjacent non-digit to its left.
- A stack is a natural data structure for this simulation since it lets us access the last added (closest left) character.
- By iterating through the string and using the stack to pair non-digits with the subsequent digit, we can effectively "cancel" out both characters.
- The process ensures that each digit leads to removal of exactly one preceding non-digit (if available).
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, since we iterate through the string once. Space Complexity: O(n), in the worst case when no digits are encountered (or before they are canceled).
Solution
The solution leverages a stack to simulate the operations. As we traverse the string from left to right:
- When encountering a non-digit character, push it onto the stack.
- When encountering a digit, pop the most recent non-digit character from the stack (which represents the closest non-digit to its left) and ignore the digit.
- Continue this process to ensure all digits are paired and removed along with their corresponding non-digits.
- Finally, the remaining characters in the stack form the resulting string.
This simulation correctly mimics the specified deletion order and ensures that all digits are removed as required.