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 made of lowercase letters and the brackets '(' and ')', remove as few brackets as possible so that the brackets left are valid, and return the result. Valid means every '(' is closed by a later ')', and every ')' closes an earlier '('. Letters always stay. When several results remove the fewest brackets, any of them is accepted.

Example 1
Input: s = "ma(t(h)s)fun)"
Output: "ma(t(h)s)fun"
Explanation: the last ')' has no match.
Example 2
Input: s = "a)b(c)d"
Output: "ab(c)d"
Example 3
Input: s = "))(("
Output: ""
Solution

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)", from left to right, counting positions from 0. At position 2 a '(' opens, and at position 4 another one opens inside it. The ')' at 6 closes the nearest bracket that is still open, the one at 4. The ')' at 8 closes the one at 2. Then the ')' at 12 arrives, and no '(' is waiting for it. Look at the picture below.

In ma(t(h)s)fun), arcs join the ( at 2 with the ) at 8 and the ( at 4 with the ) at 6. The ) at 12 is crossed out: no ( waiting. In (a(b), the ( at 2 pairs with the ) at 4, and the ( at 0 is crossed out: never closed.

In the top row, the arcs labelled "matched pairs" join the brackets that close each other, and the ')' at 12 is crossed out with "no '(' waiting: remove this ')'". Nothing later can rescue it, because a ')' can only close a '(' that came before it.

The bottom row shows the other kind of leftover. In "(a(b)", the ')' at 4 closes the nearest open bracket, the '(' at 2. The string then ends with the '(' at 0 still open, so it is crossed out as "never closed".

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 ')' at 8 instead of the one at 12, which gives "ma(t(h)sfun)", and those are accepted too.

The word that matters is nearest: a ')' always closes the '(' that opened most recently and is still open. So the open brackets behave like a pile: the one added last gets closed first. A pile used this way, last in and first out, is called a stack. Put each '(' on the stack, and let each ')' take the top one off.

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 '(' are known, and how to drop the brackets that must go.

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 '(', so the character tells us nothing new. Its position does: it says which character to remove later. A plain count of open brackets would tell us how many '(' are left over at the end, but not which ones.

When a ')' arrives and the stack is not empty, take the top position off: that '(' and this ')' are a pair. When the stack is empty, the ')' has no partner, and it is marked for removal straight away. In Java, the ArrayDeque class works as a stack through its push, pop and isEmpty methods.

Open brackets that are never closed

When do we know that a '(' is never closed? Only when the string ends, because a ')' could still arrive. The positions still on the stack at that point are exactly the unclosed ones, and each of them is marked for removal too.

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 array and overwrite each bracket to remove with '*'. The input holds only letters and brackets, so a '*' can only be a mark.

At the end, copy every character that is not '*' into a StringBuilder, a Java class that builds a string piece by piece, in one more pass.

Java Solution

The method minRemoveToMakeValid works in these steps:

  1. First, copy the string into a char array named chars with s.toCharArray(), so brackets can be marked in place. Create an empty stack named open, an ArrayDeque of positions.
  2. Walk through chars with a loop over the positions i. A '(' pushes i onto open. A ')' pops the top position if open has one, and is overwritten with '*' if open is empty. Letters are left alone.
  3. After that loop, a while loop pops every position still on open and overwrites the '(' there with '*'.
  4. Finally, a last loop appends every character of chars that is not '*' to a StringBuilder named result, and the method returns result.toString().

The main method runs the three examples, "(a(b)" with a '(' that is never closed, a string that is already valid, and the empty string.

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

Output
"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: "))((" loses all four brackets. Its two ')' come before any '(', so the first loop marks them, and its two '(' are still on open when the string ends. The fourth line, "(a(b)" -> "a(b)", drops only the '(' at position 0 and keeps the pair around b. "x(y)z" comes back unchanged, since its only two brackets are already a pair.

The while loop is easy to leave out, because the first loop already deals with every ')'. With that loop deleted, the same program printed "((" for "))((" and returned "(a(b)" unchanged, still with its unclosed '('.

Complexity

The work is one pass to pair the brackets, one round of pops for the leftover '(', and one pass to copy the kept characters.

  • 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 chars copies all n characters, and open holds n positions when the string is all '('. The StringBuilder is the output.

When only the number of brackets to fix matters, not which ones, a counter can replace the stack: see Minimum Add to Make Parentheses Valid.