Problem Description
Given a string s consisting of lowercase English letters and parentheses ('(' and ')'), remove the minimum number of parentheses so that the resulting string becomes a valid parentheses string. A valid parentheses string is defined as one that either contains only lowercase characters or is formed by proper matching of parentheses.
Key Insights
- Use a stack to record indices of unmatched '('.
- Traverse the string once to identify unmatched ')' and push indices of '('.
- Mark indices that need removal and reconstruct the valid string.
- Greedy, one-pass validation is efficient.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string
Space Complexity: O(n) in the worst case for the stack and additional storage
Solution
We can solve the problem by iterating over the string with a stack to match parentheses:
- For every character in the string:
- If the character is '(', push its index onto the stack.
- If it is ')', check if there is a matching '(' in the stack. If so, pop the top; otherwise, mark this index for removal.
- After the iteration, any indices left in the stack (representing unmatched '(') should also be marked for removal.
- Build the final string by skipping characters at marked indices. This approach ensures we only remove the minimum number of parentheses to achieve a valid string.
Code Solutions
Below are the implementations in Python, JavaScript, C++, and Java with detailed line-by-line comments.