Remove Invalid Parentheses Problem
Description
LeetCode Problem 301.
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
Example 1:
Input: s = "()())()"
Output: ["(())()","()()()"]
Example 2:
Input: s = "(a)())()"
Output: ["(a())()","(a)()()"]
Example 3:
Input: s = ")("
Output: [""]
Constraints:
- 1 <= s.length <= 25
- s consists of lowercase English letters and parentheses '(' and ')'.
- There will be at most 20 parentheses in s.
Solution
Approach: Backtracking with Removal Counts
First work out how many parentheses must go, then try only the removals of exactly that many.
Count the removals. Scan the string with a counter of unmatched '('. A ')' that finds no unmatched '(' before it can never be matched, so it must be removed (extraClose). The '(' still unmatched at the end must be removed too (extraOpen). This is the minimum, and every answer removes exactly extraOpen opening and extraClose closing parentheses.
Backtrack. remove(start, text, openLeft, closeLeft) tries each position i >= start:
- If
text[i]is')'andcloseLeft > 0, remove it and recurse fromiwithcloseLeft - 1. The same for'('andopenLeft. - When both counts reach 0, keep
textif it is balanced (a running counter never goes negative and ends at 0).
Two rules keep the results unique without a set:
- Recurse from
i, not from 0. Removals happen left to right, so the same set of positions is never removed in two different orders. - Skip a character equal to the one before it (within one loop). Removing any
')'from"))"gives the same string, so only the first of a run is tried.
For "()())()": one extra ')' and no extra '('. Removing the ')' at index 1 gives "(())()", removing the one at index 3 gives "()()()", the one at index 4 is skipped because it equals index 3, and removing the last one leaves an unbalanced string.
Complexity: O(2n · n) time in the worst case, where n is the length of s: there are at most 2n sets of removals, each producing and checking a string in O(n). In practice the counts prune most of them. O(n) recursion depth, plus the output.
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
# The fewest removals: every ')' without an earlier '(' to match, and every '(' left open at the end.
extra_open = extra_close = 0
for ch in s:
if ch == "(":
extra_open += 1
elif ch == ")":
if extra_open > 0:
extra_open -= 1
else:
extra_close += 1
results = []
def remove(start: int, text: str, open_left: int, close_left: int) -> None:
# Remove open_left more '(' and close_left more ')' from text, at index start or later.
if open_left == 0 and close_left == 0:
if is_valid(text):
results.append(text)
return
for i in range(start, len(text)):
if i > start and text[i] == text[i - 1]:
continue # removing any one of a run of equal characters gives the same string
rest = text[:i] + text[i + 1:]
if text[i] == ")" and close_left > 0:
remove(i, rest, open_left, close_left - 1)
elif text[i] == "(" and open_left > 0:
remove(i, rest, open_left - 1, close_left)
def is_valid(text: str) -> bool:
balance = 0 # '(' still waiting for a ')'
for ch in text:
if ch == "(":
balance += 1
elif ch == ")":
balance -= 1
if balance < 0:
return False
return balance == 0
remove(0, s, extra_open, extra_close)
return results
Now write it from memory
Close the write-up and solve it yourself against the tests.