Parentheses are everywhere in programming, from mathematical expressions to function calls in source code. The task is simple to state but requires careful thinking: given a string made of letters and parentheses, remove the minimum number of '(' or ')' characters so that the remaining string is valid. Because of that, when a string contains mismatched or unbalanced parentheses, it can break syntax and cause runtime errors. A valid string means every opening parenthesis has a corresponding closing parenthesis in the correct order. This is exactly where the minimum remove to make valid parentheses challenge comes in. Whether you are preparing for a technical interview or practicing algorithmic problem-solving, mastering this problem strengthens your understanding of string manipulation and stack-based logic.
What Is the Minimum Remove to Make Valid Parentheses Problem?
The minimum remove to make valid parentheses problem is a classic string-processing challenge often found on coding platforms such as LeetCode (problem 1249). You are given a string s that contains lowercase English letters and parentheses characters '(' and ')'. Here's the thing — your goal is to return a valid string by removing the fewest number of parentheses possible. If there are multiple valid results, you can return any one of them.
For example:
-
Input:
"lee(t(c)o)de)" -
Output:
"lee(t(c)o)de"or"lee(t(c)ode)" -
Input:
"a)b(c)d" -
Output:
"ab(c)d" -
Input:
"))((" -
Output:
""
Notice that the problem does not ask you to rearrange characters. Think about it: you are only allowed to delete parentheses. Letters must remain untouched and in their original positions Still holds up..
What Makes Parentheses Valid?
Before solving
Before solving, it helps to formalize the rules that define a valid parentheses string. A string is considered valid if and only if:
- Every opening parenthesis
'('has a corresponding closing parenthesis')'later in the string. - Every closing parenthesis
')'has a corresponding opening parenthesis'('earlier in the string. - Pairs are properly nested. You cannot close a parenthesis that wasn't the most recently opened unclosed one (e.g.,
)(or(()are invalid).
Essentially, as you scan the string from left to right, the count of closing parentheses should never exceed the count of opening parentheses at any point, and the total counts must be equal by the end Simple as that..
Approach 1: Stack-Based Index Tracking
The most intuitive approach uses a stack to track the indices of opening parentheses. Since we cannot modify the string in place efficiently (strings are immutable in many languages), we mark indices for removal.
Algorithm:
- Initialize an empty stack to store indices of
'('. - Initialize a
Set(or boolean array)toRemoveto store indices of parentheses to delete. - Iterate through the string with index
i:- If
s[i] == '(': Pushionto the stack. - If
s[i] == ')':- If the stack is not empty: Pop the top index (matching pair found).
- If the stack is empty: Add
itotoRemove(unmatched closing bracket).
- If
- After the loop, any indices remaining in the stack represent unmatched opening parentheses. Add all of them to
toRemove. - Build the result string by iterating through
sagain and appending characters whose indices are not intoRemove.
Why this works: The stack enforces the Last-In-First-Out (LIFO) property required for valid nesting. Unmatched closers are caught immediately because there is no opener on the stack to pair with. Unmatched openers are left in the stack at the end.
Complexity:
- Time: O(N) — We traverse the string twice.
- Space: O(N) — Stack and Set can grow up to size N in the worst case (e.g.,
((((().
Approach 2: Two-Pass Constant Space (Excluding Output)
We can optimize space to O(1) auxiliary space (ignoring the output string builder) by using two linear passes without a stack. We track a balance counter instead Not complicated — just consistent. Worth knowing..
Algorithm:
- First Pass (Left-to-Right): Remove invalid
')'.- Initialize
balance = 0and aStringBuilder(or list)sb. - Iterate through
s:- If char is
'(':balance++, append tosb. - If char is
')':- If
balance == 0: Skip this char (invalid closer). - Else:
balance--, append tosb.
- If
- If char is a letter: Append to
sb.
- If char is
- At this stage,
sbhas no invalid')', but may have extra'('(indicated bybalance > 0).
- Initialize
- Second Pass (Right-to-Left): Remove excess
'('.- Initialize
resultbuilder. - Iterate
sbbackwards:- If char is
'('andbalance > 0:balance--, skip this char (remove excess opener). - Else: Prepend char to
result(or append to a new builder and reverse at the end).
- If char is
- Initialize
- Return
result.
Why this works: The first pass ensures no prefix has more closers than openers. The balance at the end of pass one equals the number of unmatched openers. The second pass removes exactly that many openers from the right side, preserving the leftmost openers which are more likely to have valid matches.
Complexity:
- Time: O(N) — Two passes.
- Space: O(N) for the output builder, but O(1) auxiliary space (just integer counters).
Edge Cases to Consider
- Empty String: Returns empty string.
- No Parentheses: Returns original string (e.g.,
"abc"). - All Invalid:
" ))(( "returns"". - Nested Valid:
"(a(b)c)"returns same string. - Letters Interspersed: Logic must strictly ignore letters during balance checks but preserve them in output.
Practical Implementation Tips
- Language Specifics: In Python, use a
listas a stack and asetfor removal indices; join a list comprehension for the final string. In Java, useDeque<Integer>andStringBuilder. In C++, usevector<int>as stack andstringbuilder. - Mutability: If the language allows mutable strings (like C++
std::stringor RustString), you can mark characters with a placeholder (e.g.,*) during the first pass and erase them in a second pass, avoiding a