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 made only of the characters ( and ), return the smallest number of brackets you must insert to make it valid. You may insert either character at any position. A string is valid when every ( is closed by a ) somewhere after it, and every ) closes a ( somewhere before it.

Example 1
Input: s = "())"
Output: 1
Explanation: the last ')' has nothing to close; add one '('.
Example 2
Input: s = "((("
Output: 3
Example 3
Input: s = ")("
Output: 2
Explanation: one '(' before the start and one ')' after the end.
Solution

The Idea

Brackets in an expression such as (2 + 3) * (4 - 1) come in pairs: each ( opens a group, and a later ) closes it. Take away the numbers and signs, and what is left is ()(), a string of brackets. This problem hands us such a string, possibly broken, and asks how few brackets it takes to repair it.

Read Example 1, ()), from left to right. The first ( opens a group and the next ) closes it. Then the last ) arrives while no group is open. Nothing before it can be its partner, so a ( has to be inserted in front of it, which gives ()(). One insertion is enough.

Example 3, )(, shows the other way a string can break. The ) at the start has nothing before it, and the ( at the end has nothing after it to close it. Each needs a partner of its own, so the answer is 2.

So there are two kinds of broken bracket: a ) that finds no open group, and a ( that is never closed. How can we spot both in one reading, without trying every place a bracket could be inserted?

By keeping count of the ( brackets still waiting for a partner. Each ( adds one to the count. A ) closes one of them if any are waiting; if none are, it is a broken ). When the string ends, every ( still waiting is broken too. Look at the picture below, which reads the string )(() one character at a time.

Reading )(() from left to right. The first ) comes while no ( is waiting, so a ( is added before it. The two ( raise the waiting count to 2, and the last ) lowers it to 1. That 1 is still waiting at the end, so a ) is added. The answer is 1 + 1 = 2, giving ()(()).

The top row, "character", lists the string. The first ), in orange, arrives when the row "'(' still waiting" shows 0. It has nothing to close, so the row "')' found with nothing to close" goes up to 1, and the note under it says to add a ( before it. The two ( that follow raise the waiting count to 2, and the last ) closes one of them, leaving 1.

That 1 is still waiting when the string ends, so the note on the right says to add a ) at the end. The answer is 1 + 1 = 2, and adding both brackets gives ()(()). One pass and two counts are all the problem needs.

Solution Approach

Turning that idea into code means settling four things: what a ) does when it arrives, what happens to the ( still waiting at the end, why the counts give the fewest insertions, and where to keep the waiting brackets.

Handling a closing bracket

When a ) arrives and several ( are waiting, which one should it close? It does not matter, because they are all the same character. Closing one right away never hurts: that ( would otherwise need an inserted ) later.

If no ( is waiting, nothing further along the string can help, because a ) needs its partner before it. So a ( must be inserted, and the count of those insertions goes up at once.

Brackets still waiting at the end

What about the ( brackets still waiting when the string runs out? No ) is left to close them, so each one needs a ) inserted after it, for example at the very end. The answer is the number of broken ) plus the number of ( still waiting.

Why the count is the fewest

Could a cleverer choice of positions use fewer insertions? No. An inserted ( can be the partner of only one ), and an inserted ) of only one (. Every bracket counted this way has no partner in the string, so each needs a new one of its own.

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 ( on a stack and take one off when a ) arrives. Here every item on that stack would be the same (, so the only thing it tells us is how many items it holds. A single int holds that number just as well.

Java Solution

The method minAddToMakeValid works in these steps:

  1. First, set two counters to 0: open, the number of ( still waiting for a partner, and added, the number of ( to insert, one for each ) that finds nothing to close.
  2. Walk through s with a for loop, reading each character into c with s.charAt(i).
  3. If c is (, increase open.
  4. Otherwise c is ). If open is above 0, the bracket closes a waiting (, so decrease open. If open is 0, increase added.
  5. After the loop, return added + open. At this point open counts the ( that still need a ) after them.

The main method runs the three examples, the string )(() from the picture, an empty string, a string that is already valid, and ))(((, which is broken at both ends.

Java
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:

Output
"())" -> 1
"(((" -> 3
")(" -> 2
")(()" -> 2
"" -> 0
"()()" -> 0
"))(((" -> 5

Look at the line "(((" -> 3. No ) ever arrives, so added stays 0 and all three come from open at the end. A version that returns added alone prints 0 for this string. The line ")(()" -> 2 is the string from the picture, with one bracket of each kind.

The empty string and "()()" both print 0, since a valid string needs nothing inserted. In the last line, "))(((" -> 5, the two ) at the start find nothing to close, so added reaches 2. The three ( are still waiting at the end, and 2 + 3 gives 5.

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 s once and only changes one counter for it.
  • Space: O(1), because open and added are the only storage, however long s is. Reading with s.charAt(i) avoids copying the string into a new array, as toCharArray() would.

When the task is to remove brackets instead of inserting them, and to return the repaired string, see Minimum Remove to Make Valid Parentheses.