Algo-Sim › Recursion & Backtracking

Remove Invalid Parentheses

Hard · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Remove the fewest parentheses to make a string valid, listing every result: count the removals first, then DFS with duplicate skipping.

Problem

Given a string s of parentheses and letters, remove the minimum number of parentheses to make it valid. Return every distinct valid string that can be obtained, in any order.

Constraints

Edge cases to test

Follow-up questions

Why count removals first?
Knowing exactly how many ( and ) to drop bounds the DFS to minimal solutions.
What is the BFS alternative?
Remove one character per level and stop at the first level with a valid string: simpler, but explores more states.

Solution

Java

List<String> result = new ArrayList<>();

List<String> removeInvalidParentheses(String s) {
    int l = 0, r = 0;           // unmatched '(' and ')' that must go
    for (char c : s.toCharArray()) {
        if (c == '(') l++;
        else if (c == ')') { if (l > 0) l--; else r++; }
    }
    dfs(s, 0, l, r);
    return result;
}

void dfs(String s, int start, int l, int r) {
    if (l == 0 && r == 0) {
        if (valid(s)) result.add(s);
        return;
    }
    for (int i = start; i < s.length(); i++) {
        // Removing either of two equal neighbours gives the same string.
        if (i > start && s.charAt(i) == s.charAt(i - 1)) continue;
        char c = s.charAt(i);
        String t = s.substring(0, i) + s.substring(i + 1);
        if (c == '(' && l > 0) dfs(t, i, l - 1, r);
        if (c == ')' && r > 0) dfs(t, i, l, r - 1);
    }
}

boolean valid(String s) {
    int open = 0;
    for (char c : s.toCharArray()) {
        if (c == '(') open++;
        else if (c == ')' && --open < 0) return false;
    }
    return open == 0;
}

Python

def remove_invalid_parentheses(s):
    def valid(t):
        bal = 0
        for c in t:
            if c == "(":
                bal += 1
            elif c == ")":
                bal -= 1
                if bal < 0:
                    return False
        return bal == 0

    result = []

    def dfs(t, start, l, r):
        if l == 0 and r == 0:
            if valid(t):
                result.append(t)
            return
        for i in range(start, len(t)):
            # Removing either of two equal neighbours gives the same string.
            if i > start and t[i] == t[i - 1]:
                continue
            u = t[:i] + t[i + 1:]
            if t[i] == "(" and l > 0:
                dfs(u, i, l - 1, r)
            if t[i] == ")" and r > 0:
                dfs(u, i, l, r - 1)

    l = r = 0               # unmatched '(' and ')' that must go
    for c in s:
        if c == "(":
            l += 1
        elif c == ")":
            if l:
                l -= 1
            else:
                r += 1
    dfs(s, 0, l, r)
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<string> result = {};

    vector<string> removeInvalidParentheses(string &s) {
        int l = 0, r = 0; // unmatched '(' and ')' that must go
        for (char c : s) {
            if (c == '(') l++;
            else if (c == ')') {
                if (l > 0) l--;
                else r++;
            }
        }
        dfs(s, 0, l, r);
        return result;
    }

    void dfs(string s, int start, int l, int r) {
        if (l == 0 && r == 0) {
            if (valid(s)) result.push_back(s);
            return;
        }
        for (int i = start; i < int(s.size()); i++) {
            // Removing either of two equal neighbours gives the same string.
            if (i > start && s[i] == s[i - 1]) continue;
            char c = s[i];
            string t = s.substr(0, i) + s.substr(i + 1);
            if (c == '(' && l > 0) dfs(t, i, l - 1, r);
            if (c == ')' && r > 0) dfs(t, i, l, r - 1);
        }
    }

    bool valid(const string &s) {
        int open = 0;
        for (char c : s) {
            if (c == '(') open++;
            else if (c == ')' && --open < 0) return false;
        }
        return open == 0;
    }
};

More Recursion & Backtracking problems