Minimum Remove to Make Valid Parentheses
Remove as few brackets as possible from a string so that every bracket left has a partner.
Given a string s'('')''('')'')''('
Example 1
Output: "ma(t(h)s)fun"
Explanation: the last ')' has no match.
Example 2
Output: "ab(c)d"
Example 3
Output: ""
The Idea
You have probably seen a code editor light up the partner of the bracket under the cursor, and mark a bracket in red when it has no partner. This problem needs the same pairing, and then removes the brackets that are left without a partner.
Read Example 1, "ma(t(h)s)fun)"'('')'')'')''('
In the top row, the arcs labelled "matched pairs" join the brackets that close each other, and the ')'')''('
The bottom row shows the other kind of leftover. In "(a(b)"')''(''('
So which brackets should go? Since brackets can only be removed, never added, every bracket without a partner costs one removal. Removing exactly those leaves a valid string with the fewest removals. Other answers may remove a different bracket of the same kind, such as the ')'"ma(t(h)sfun)"
The word that matters is nearest: a ')''(''('')'
Solution Approach
The slow way, trying every set of removals, shows why one pass is worth it. After that, three things need settling: what the stack holds, when the leftover '('
Trying every set of removals
Why not remove brackets in every possible way, and keep a valid result with the fewest removals? Each bracket is either kept or removed, so a string with 20 brackets has about a million ways to choose. Pairing brackets with a stack needs one pass from left to right.
What the stack holds
Should the stack hold the brackets themselves? Every bracket on it is a '(''('
When a ')''('')'')'ArrayDequepushpopisEmpty
Open brackets that are never closed
When do we know that a '('')'
Dropping the marked brackets
How do we remove characters without shifting the rest each time? Removing one character from the middle of a string moves everything after it. Instead, copy the string into a char'*''*'
At the end, copy every character that is not '*'StringBuilder
Java Solution
The method minRemoveToMakeValid
- First, copy the string into a
array namedchar withchars , so brackets can be marked in place. Create an empty stack nameds.toCharArray() , anopen of positions.ArrayDeque - Walk through
with a loop over the positionschars . Ai pushes'(' ontoi . Aopen pops the top position if')' has one, and is overwritten withopen if'*' is empty. Letters are left alone.open - After that loop, a
loop pops every position still onwhile and overwrites theopen there with'(' .'*' - Finally, a last loop appends every character of
that is notchars to a'*' namedStringBuilder , and the method returnsresult .result.toString()
The main"(a(b)"'('
import java.util.ArrayDeque;
import java.util.Deque;
public class MinRemoveToMakeValidParentheses {
public static String minRemoveToMakeValid(String s) {
char[] chars = s.toCharArray();
Deque<Integer> open = new ArrayDeque<>(); // positions of '(' still waiting for a ')'
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '(') {
open.push(i);
} else if (chars[i] == ')') {
if (open.isEmpty()) {
chars[i] = '*'; // no '(' waiting: remove this ')'
} else {
open.pop(); // matches the nearest waiting '('
}
}
}
while (!open.isEmpty()) {
chars[open.pop()] = '*'; // '(' never closed: remove it
}
StringBuilder result = new StringBuilder();
for (char c : chars) {
if (c != '*') {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String[] inputs = {"ma(t(h)s)fun)", "a)b(c)d", "))((", "(a(b)", "x(y)z", ""};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + minRemoveToMakeValid(s) + "\"");
}
}
}
Running it prints:
"ma(t(h)s)fun)" -> "ma(t(h)s)fun"
"a)b(c)d" -> "ab(c)d"
"))((" -> ""
"(a(b)" -> "a(b)"
"x(y)z" -> "x(y)z"
"" -> ""
Look at the third line: "))(("')''(''('open"(a(b)" -> "a(b)"'('b"x(y)z"
The while')'"((""))((""(a(b)"'('
Complexity
The work is one pass to pair the brackets, one round of pops for the leftover '('
- Time: O(n), because the first loop looks at each of the n characters once, each position is pushed and popped at most once, and the copy reads each character once more.
- Space: O(n), because
copies all n characters, andchars holds n positions when the string is allopen . The'(' is the output.StringBuilder
When only the number of brackets to fix matters, not which ones, a counter can replace the stack: see