Remove Invalid Parentheses

Pattern: Recursion trees

hard

Breadth-first search over removals. Level 0 is the string itself, level 1 every string with one bracket removed, and so on. The first level that contains a valid string holds every answer with the fewest removals.

The problem

Given a string of brackets and letters, remove the fewest brackets so that the result is valid (every bracket matched, letters ignored). Return every distinct valid result with that fewest number of removals. For example, "()())()" gives (())() and ()()(), "(a)())()" gives (a())() and (a)()(), and ")(" gives only the empty string.

The function name removeInvalidParentheses matches LeetCode. Use the link above for the exact statement and limits. The tests compare the answers after sorting.

Think first

  • How can you search by "number of removals" in increasing order?
  • When can the search stop?
  • How do you avoid working on the same string twice?

Hints

    Brute force, and why it fails

    Try every subset of characters to remove and keep the longest valid results: O(2ⁿ × n). Breadth-first search stops at the first good level, which is usually far sooner. A depth-first search that first counts how many ( and ) must go is another standard approach.

    The key insight

    "Fewest removals" is a shortest-path question where each step removes one bracket. Breadth-first search finds all shortest answers by stopping at the first level that has any.

    Dry run

    level0

    s = ()())(). It is not valid, since the fifth character closes nothing.

    Step 1 of 4

    The plan

    level = {s}, seen = {s}
    while level is not empty:
        valid = strings in level that are valid
        if valid is not empty: return valid
        next = for each string, every way to remove one bracket, not seen before
        level = next
    

    Complexity

    Time
    O(2ⁿ × n) worst
    Space
    O(2ⁿ × n) worst

    In the worst case many levels are explored, each string checked in O(n). Short inputs (LeetCode allows 25 characters) finish quickly in practice.

    Edge cases

    • Already valid: returned as it is.
    • Nothing can be kept, as in ")(": the empty string.
    • Letters only: unchanged.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<String> removeInvalidParentheses(String s) {
            List<String> out = new ArrayList<>();
            Set<String> seen = new HashSet<>();
            Queue<String> level = new LinkedList<>();       // breadth-first: level d holds strings with d removals
            level.add(s);
            seen.add(s);
            boolean found = false;
            while (!level.isEmpty() && !found) {
                int size = level.size();
                for (int q = 0; q < size; q++) {
                    String cur = level.poll();
                    if (valid(cur)) { out.add(cur); found = true; }   // the first level with a valid string is the answer
                    if (found) continue;
                    for (int i = 0; i < cur.length(); i++) {
                        char c = cur.charAt(i);
                        if (c != '(' && c != ')') continue;
                        String next = cur.substring(0, i) + cur.substring(i + 1);   // remove one bracket
                        if (seen.add(next)) level.add(next);
                    }
                }
            }
            return out;
        }
    
        private boolean valid(String t) {
            int depth = 0;
            for (char c : t.toCharArray()) {
                if (c == '(') depth++;
                else if (c == ')' && --depth < 0) return false;
            }
            return depth == 0;
        }
    }

    C++

    class Solution {
    public:
        vector<string> removeInvalidParentheses(string s) {
            vector<string> out;
            unordered_set<string> seen = {s};
            vector<string> level = {s};                     // breadth-first: level d holds strings with d removals
            while (!level.empty()) {
                for (const string& cur : level) if (valid(cur)) out.push_back(cur);
                if (!out.empty()) break;                    // the first level with a valid string is the answer
                vector<string> next;
                for (const string& cur : level) {
                    for (size_t i = 0; i < cur.size(); i++) {
                        if (cur[i] != '(' && cur[i] != ')') continue;
                        string t = cur.substr(0, i) + cur.substr(i + 1);   // remove one bracket
                        if (seen.insert(t).second) next.push_back(t);
                    }
                }
                level = next;
            }
            return out;
        }
    
        bool valid(const string& t) {
            int depth = 0;
            for (char c : t) {
                if (c == '(') depth++;
                else if (c == ')' && --depth < 0) return false;
            }
            return depth == 0;
        }
    };

    Python

    class Solution:
        def removeInvalidParentheses(self, s: str) -> list[str]:
            def valid(t: str) -> bool:
                depth = 0
                for c in t:
                    if c == "(":
                        depth += 1
                    elif c == ")":
                        depth -= 1
                        if depth < 0:
                            return False
                return depth == 0
    
            level, seen = {s}, {s}                  # breadth-first: level d holds strings with d removals
            while level:
                out = [t for t in level if valid(t)]
                if out:
                    return out                      # the first level with a valid string is the answer
                nxt = set()
                for cur in level:
                    for i, c in enumerate(cur):
                        if c in "()":
                            t = cur[:i] + cur[i + 1:]   # remove one bracket
                            if t not in seen:
                                seen.add(t)
                                nxt.add(t)
                level = nxt
            return []

    Common mistakes

    • Continuing past the first good level, which adds answers with more removals.
    • Removing letters as well as brackets.
    • Returning duplicates when the same string is reached by removing different equal brackets.

    Similar problems