Remove Invalid Parentheses

Remove the minimum parentheses to make s valid; return all distinct resulting strings via BFS or targeted DFS.

Hard
Time O(n * 2^n) Space O(n)
LeetCode
6 min read
backtracking string

Problem#

Given a string with letters, (, and ), remove the minimum number of parentheses so the result is valid. Return all unique results.

Examples#

  • "()())()"["(())()","()()()"]
  • "(a)())()"["(a())()","(a)()()"]

Constraints#

  • 1 <= s.length <= 25.

Hints#

Hint 1
First compute the number of misplaced ( and ) to delete. Then DFS, restricting deletions to those budgets.

Approach#

Single left-to-right pass computes excess ) (r) and excess ( (l). Backtracking: at each position, optionally skip the current paren (if budget allows), or keep it. Track running open count; reject paths that go invalid. Add to result on reaching end with both budgets exhausted and balanced.

Solution#

Remove Invalid Parentheses
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
int l = 0, r = 0;
for (char c : s) {
if (c == '(') ++l;
else if (c == ')') { if (l > 0) --l; else ++r; }
}
set<string> out;
function<void(int,int,int,int,string&)> dfs = [&](int i, int open, int rl, int rr, string& path) {
if (i == (int)s.size()) {
if (open == 0 && rl == 0 && rr == 0) out.insert(path);
return;
}
char c = s[i];
if (c == '(' && rl > 0) dfs(i + 1, open, rl - 1, rr, path);
else if (c == ')' && rr > 0) dfs(i + 1, open, rl, rr - 1, path);
path.push_back(c);
if (c == '(') dfs(i + 1, open + 1, rl, rr, path);
else if (c == ')') { if (open > 0) dfs(i + 1, open - 1, rl, rr, path); }
else dfs(i + 1, open, rl, rr, path);
path.pop_back();
};
string path;
dfs(0, 0, l, r, path);
return {out.begin(), out.end()};
}
};

Editorial#

Computing (l, r) budgets upfront prunes the search to only deletions consistent with the minimum count. The set deduplicates results from independent branches that produce the same string.

Complexity#

  • Time: O(n × 2^n) worst case.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.