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 AB where 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
Parentheses Balancing ProcessInput: "((a)b)c)"(idx 0(idx 1aidx 2)idx 3bidx 4)idx 5cidx 6)idx 7Processing Steps:1. '(' at idx 0 โ†’ Push to stack [0]2. '(' at idx 1 โ†’ Push to stack [0,1]3. 'a' at idx 2 โ†’ Keep as is4. ')' at idx 3 โ†’ Match with idx 1, pop โ†’ [0]5. 'b' at idx 4 โ†’ Keep as is6. ')' at idx 5 โ†’ Match with idx 0, pop โ†’ []7. 'c' at idx 6 โ†’ Keep as is8. ')' at idx 7 โ†’ No match! Mark for removalResult: "((a)b)c"Removed: ')' at index 7
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!
Asked in
Meta 42 Google 38 Amazon 31 Microsoft 24
89.2K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen