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 Parentheses INPUT String s = "()())" ( idx 0 ) idx 1 ( idx 2 ) idx 3 ) idx 4 Extra ')' at index 4 makes string invalid Valid String Rules: 1. Empty or lowercase only 2. AB where A,B valid 3. (A) where A is valid s = "()())" ALGORITHM STEPS Two-Pass Optimal 1 Pass 1: Left to Right Track open count, mark extra ')' for removal 2 Pass 2: Right to Left Track close count, mark extra '(' for removal 3 Build Result Skip marked indices, keep valid chars 4 Return String O(n) time, O(n) space Pass 1 Trace: '(' open=1 ')' open=0 '(' open=1 ')' open=0 ')' REMOVE! Index 4 marked for removal FINAL RESULT After removing index 4: ( ) ( ) All parentheses matched! Output: "()()" OK - Valid! Removed: 1 character Result length: 4 Key Insight: Two-pass approach handles both types of invalid parentheses: Pass 1 (left-to-right) finds unmatched ')' while Pass 2 (right-to-left) finds unmatched '('. This ensures minimum removals with O(n) complexity. Alternative: Use a stack to track indices of unmatched parentheses, then build result excluding them. TutorialsPoint - Minimum Remove to Make Valid Parentheses | Two-Pass Optimal Approach
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