SDE & MLE Prep

301. Remove Invalid Parentheses

Problem

Remove the minimum number of parentheses from s (which may also contain letters) to make it valid, and return every distinct result.

Example: "()())()" → ["(())()","()()()"]; ")(" → [""]

Constraints: length ≤ 25; at most 20 parentheses.

BFS by number of removals: level 0 = the string, level d = all strings with d characters removed. The first level that contains valid strings is the answer (minimum removals); collect all of them, deduped with a set.

Complexity: exponential worst case; fine for n ≤ 25.

class Solution:
    def removeInvalidParentheses(self, s: str) -> List[str]:
        def valid(t):
            bal = 0
            for ch in t:
                if ch == "(":
                    bal += 1
                elif ch == ")":
                    bal -= 1
                    if bal < 0:
                        return False
            return bal == 0

        level = {s}
        while True:
            good = [t for t in level if valid(t)]
            if good:
                return good
            level = {t[:i] + t[i + 1:] for t in level for i in range(len(t)) if t[i] in "()"}