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 "()"}
assert sorted(Solution().removeInvalidParentheses("()())()")) == ["(())()", "()()()"]
assert sorted(Solution().removeInvalidParentheses("(a)())()")) == ["(a())()", "(a)()()"]
assert Solution().removeInvalidParentheses(")(") == [""]
class Solution {
public List<String> removeInvalidParentheses(String s) {
Set<String> level = new HashSet<>(List.of(s));
while (true) {
List<String> good = new ArrayList<>();
for (String t : level) if (valid(t)) good.add(t);
if (!good.isEmpty()) return good;
Set<String> next = new HashSet<>();
for (String t : level)
for (int i = 0; i < t.length(); i++)
if (t.charAt(i) == '(' || t.charAt(i) == ')') next.add(t.substring(0, i) + t.substring(i + 1));
level = next;
}
}
private boolean valid(String t) {
int bal = 0;
for (char c : t.toCharArray()) {
if (c == '(') bal++;
else if (c == ')' && --bal < 0) return false;
}
return bal == 0;
}
}
func removeInvalidParentheses(s string) []string {
valid := func(t string) bool {
bal := 0
for i := 0; i < len(t); i++ {
if t[i] == '(' {
bal++
} else if t[i] == ')' {
if bal--; bal < 0 {
return false
}
}
}
return bal == 0
}
level := map[string]bool{s: true}
for { // BFS by number of removals: the first level with a valid string wins
good := []string{}
for t := range level {
if valid(t) {
good = append(good, t)
}
}
if len(good) > 0 {
return good
}
next := map[string]bool{}
for t := range level {
for i := 0; i < len(t); i++ {
if t[i] == '(' || t[i] == ')' {
next[t[:i]+t[i+1:]] = true
}
}
}
level = next
}
}