Minimum Remove to Make Valid Parentheses - Problem

Given a string s containing '(', ')' and lowercase English characters, your task is to remove the minimum number of parentheses to make the resulting string valid.

A valid parentheses string is defined as:

  • The empty string, or contains only lowercase characters
  • It can be written as AB (A concatenated with B), where A and B are valid strings
  • It can be written as (A), where A is a valid string

Return any valid string after removing the minimum number of parentheses.

Input & Output

Example 1 — Extra Closing Parenthesis
$ Input: s = "()())"
Output: "()()"
💡 Note: Remove the extra closing parenthesis at position 4. The string "()()" has valid balanced parentheses.
Example 2 — Extra Opening Parenthesis
$ Input: s = "((("
Output: ""
💡 Note: All three opening parentheses are unmatched, so remove all of them to get empty string.
Example 3 — Mixed with Letters
$ Input: s = "(a))b)"
Output: "(a)b"
💡 Note: Remove one closing parenthesis after 'a' and the closing parenthesis after 'b' to make it valid.

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '(' , ')' or lowercase English letter

Visualization

Tap to expand
Minimum Remove to Make Valid ParenthesesInput: "()())"Invalid - extra closing bracketOutput: "()()"Valid - balanced bracketsAlgorithm Steps1. Scan left-to-right: count opening brackets, remove unmatched closing2. Track excess opening brackets that have no matching closing3. Second pass: remove excess opening brackets to balance the stringResult: Minimum characters removed for valid parentheses
Understanding the Visualization
1
Input
String with unmatched parentheses: "()())"
2
Process
Identify and remove unmatched brackets
3
Output
Valid parentheses string: "()()"
Key Takeaway
🎯 Key Insight: Use a counter to track unmatched opening brackets and immediately skip unmatched closing brackets
Asked in
Facebook 65 Google 45 Amazon 38
85.4K 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