Minimum Add to Make Parentheses Valid
Find the fewest brackets to insert so that every bracket in a string has a partner.
Given a string s()())(
Example 1
Output: 1
Explanation: the last ')' has nothing to close; add one '('.
Example 2
Output: 3
Example 3
Output: 2
Explanation: one '(' before the start and one ')' after the end.
The Idea
Brackets in an expression such as (2 + 3) * (4 - 1)()()()
Read Example 1, ())())(()()
Example 3, )()(
So there are two kinds of broken bracket: a )(
By keeping count of the (())()(()
The top row, "character", lists the string. The first )(()
That 1 is still waiting when the string ends, so the note on the right says to add a )()(())
Solution Approach
Turning that idea into code means settling four things: what a )(
Handling a closing bracket
When a )(()
If no ()(
Brackets still waiting at the end
What about the ()))(
Why the count is the fewest
Could a cleverer choice of positions use fewer insertions? No. An inserted ())(
That is what saves us from the slow way: trying every set of positions and every choice of bracket, then checking each result. The number of such tries grows very fast as the string gets longer, while counting reads it once.
A counter in place of a stack
A stack is a pile of items where you add and remove only at the top. The usual way to match brackets is to put each ()(int
Java Solution
The method minAddToMakeValid
- First, set two counters to 0:
, the number ofopen still waiting for a partner, and( , the number ofadded to insert, one for each( that finds nothing to close.) - Walk through
with as loop, reading each character intofor withc .s.charAt(i) - If
isc , increase( .open - Otherwise
isc . If) is above 0, the bracket closes a waitingopen , so decrease( . Ifopen is 0, increaseopen .added - After the loop, return
. At this pointadded + open counts theopen that still need a( after them.)
The main)(()))(((
public class MinAddToMakeParenthesesValid {
public static int minAddToMakeValid(String s) {
int open = 0; // '(' still waiting for a ')'
int added = 0; // '(' to insert, one for each ')' that finds none waiting
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
open++;
} else if (open > 0) {
open--; // this ')' closes one waiting '('
} else {
added++; // nothing to close: a '(' must go before it
}
}
return added + open; // each '(' still waiting needs a ')' after it
}
public static void main(String[] args) {
String[] tests = {"())", "(((", ")(", ")(()", "", "()()", "))((("};
for (String s : tests) {
System.out.println("\"" + s + "\" -> " + minAddToMakeValid(s));
}
}
}
Running it prints:
"())" -> 1
"(((" -> 3
")(" -> 2
")(()" -> 2
"" -> 0
"()()" -> 0
"))(((" -> 5
Look at the line "(((" -> 3)addedopenadded")(()" -> 2
The empty string and "()()""))(((" -> 5)added(
Complexity
The method reads the string once and keeps only two numbers.
- Time: O(n), because the loop reads each of the n brackets in
once and only changes one counter for it.s - Space: O(1), because
andopen are the only storage, however longadded is. Reading withs avoids copying the string into a new array, ass.charAt(i) would.toCharArray()
When the task is to remove brackets instead of inserting them, and to return the repaired string, see