Minimum Remove to Make Valid Parentheses - Problem
Given a string containing parentheses '(', ')' and lowercase English characters, your task is to remove the minimum number of parentheses to make the string valid.
A valid parentheses string is defined as:
- Empty string or contains only lowercase characters
- Can be written as
ABwhere both A and B are valid strings - Can be written as
(A)where A is a valid string
Goal: Return any valid string after removing the minimum number of parentheses.
Example: "()())" โ "(())" or "()()"
Input & Output
example_1.py โ Basic Case
$
Input:
s = "()())"
โบ
Output:
"(())" or "()()"
๐ก Note:
We have one extra closing parenthesis. We can remove it to get either "(())" or "()()" - both are valid.
example_2.py โ Extra Opening
$
Input:
s = "((("
โบ
Output:
""
๐ก Note:
All parentheses are opening brackets with no closing matches, so we remove all of them.
example_3.py โ Mixed with Letters
$
Input:
s = "(v)())()"
โบ
Output:
"(v)()()"
๐ก Note:
Remove one extra closing parenthesis. Letters remain unchanged as they don't affect validity.
Constraints
- 1 โค s.length โค 105
- s[i] is either '(' or ')' or lowercase English letter
- Return any valid answer - multiple solutions may exist
Visualization
Tap to expand
Understanding the Visualization
1
Track Opening
Use stack to remember positions of unmatched '(' characters
2
Match Closing
When we see ')', try to match with most recent '(' from stack
3
Clean Up
Remove all unmatched parentheses (both '(' and ')') from final result
Key Takeaway
๐ฏ Key Insight: Use a stack to track unmatched opening parentheses and immediately identify invalid closing ones - this gives us the minimum removals in just one pass!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code