Remove Invalid Parentheses
Remove Invalid Parentheses is a hard recursion & backtracking problem solved with the pick / not-pick pattern.
The best approach, optimal (count the removals, then backtrack), runs in O(2^n · n) time and O(n) besides the output space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from breadth-first search by number of removals up.
Problem
You are given a string s made of '(', ')' and lowercase letters.
Remove as few brackets as possible so that the brackets in the string become valid: every ) closes an earlier ( that is still open, and no ( is left open at the end. Letters do not affect validity.
Return every distinct valid string you can get with that minimum number of removals. Each string appears once, and the list may be in any order.
Examples
Example 1
- Input
s = "(a)())"- Output
["(a())", "(a)()"]- Why
- There is one ')' too many, so one removal is the minimum. Removing either of the two ')' in the middle gives "(a())" or "(a)()". Removing the last ')' gives "(a)()" again, which is listed once.
Example 2
- Input
s = "x)("- Output
["x"]- Why
- The ')' closes nothing and the '(' is never closed. Both must go, and only one string is left.
Example 3
- Input
s = ")(("- Output
[""]- Why
- No bracket can be kept, so all three are removed and the empty string is the only answer.
Constraints
1 <= s.length <= 25s[i]is'(',')'or a lowercase English letter.scontains at most20brackets.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 21 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Breadth-first search by number of removals | O(2^n · n) | O(2^n · n) |
| Optimal (count the removals, then backtrack) | O(2^n · n) | O(n) besides the output |
1Breadth-first search by number of removals
O(2^n · n)In the worst case the search visits a large share of the 2^n subsets of brackets, and each one costs O(n) to build and to check.O(2^n · n)A level and the seen set can hold that many strings of length up to n.Level 0 is the string itself. Level 1 holds every distinct string made by deleting one bracket, level 2 every string made by deleting two, and so on. Check the levels in order. The first level that contains at least one valid string uses the minimum number of removals, and all its valid strings are the answer. A set of strings already seen keeps duplicates out.
- level = {s}, seen = {s}.
- If some strings in level are valid, return all of them.
- Otherwise build the next level: for every string and every bracket in it, delete that bracket; keep the result if it is not in seen.
- Repeat. Removing every bracket always leaves a valid string, so the loop ends.
class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> result = new ArrayList<>();
Set<String> seen = new HashSet<>();
List<String> level = new ArrayList<>();
level.add(s);
seen.add(s);
while (true) {
for (String t : level) if (isValid(t)) result.add(t);
if (!result.isEmpty()) return result;
List<String> next = new ArrayList<>();
for (String t : level) {
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if (c != '(' && c != ')') continue;
String u = t.substring(0, i) + t.substring(i + 1);
if (seen.add(u)) next.add(u);
}
}
level = next;
}
}
private boolean isValid(String t) {
int open = 0;
for (char c : t.toCharArray()) {
if (c == '(') open++;
else if (c == ')' && --open < 0) return false;
}
return open == 0;
}
}class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
seen = {s}
level = [s]
while True:
result = [t for t in level if self.isValid(t)]
if result:
return result
nxt = []
for t in level:
for i, c in enumerate(t):
if c != "(" and c != ")":
continue
u = t[:i] + t[i + 1:]
if u not in seen:
seen.add(u)
nxt.append(u)
level = nxt
def isValid(self, t: str) -> bool:
open_count = 0
for c in t:
if c == "(":
open_count += 1
elif c == ")":
open_count -= 1
if open_count < 0:
return False
return open_count == 0class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> result;
unordered_set<string> seen{s};
vector<string> level{s};
while (true) {
for (const string& t : level) if (isValid(t)) result.push_back(t);
if (!result.empty()) return result;
vector<string> next;
for (const string& t : level) {
for (size_t i = 0; i < t.size(); i++) {
char c = t[i];
if (c != '(' && c != ')') continue;
string u = t.substr(0, i) + t.substr(i + 1);
if (seen.insert(u).second) next.push_back(u);
}
}
level = next;
}
}
private:
bool isValid(const string& t) {
int open = 0;
for (char c : t) {
if (c == '(') open++;
else if (c == ')' && --open < 0) return false;
}
return open == 0;
}
};function removeInvalidParentheses(s) {
const seen = new Set([s]);
let level = [s];
while (true) {
const result = level.filter(isValid);
if (result.length > 0) return result;
const next = [];
for (const t of level) {
for (let i = 0; i < t.length; i++) {
const c = t[i];
if (c !== "(" && c !== ")") continue;
const u = t.slice(0, i) + t.slice(i + 1);
if (!seen.has(u)) {
seen.add(u);
next.push(u);
}
}
}
level = next;
}
}
function isValid(t) {
let open = 0;
for (const c of t) {
if (c === "(") open++;
else if (c === ")" && --open < 0) return false;
}
return open === 0;
}2Optimal (count the removals, then backtrack)
O(2^n · n)Each of the up to n brackets is either kept or removed, so there are at most 2^n paths, and recording a result costs O(n). The fixed removal budgets and the open check cut most paths early.O(n) besides the outputThe recursion depth and the path being built are both at most n, plus the set of results.First work out exactly how many brackets of each kind must go. Scan once with an open counter: a ')' that arrives with nothing open must be removed (right++), and every '(' still open at the end must be removed (left). Those two numbers are the minimum, so we never need to search other levels. Then walk the string with backtracking. At each bracket there are two choices: spend one removal of its kind on it (if any are left), or keep it. Keeping a ')' is only allowed while something is open, so the prefix built so far never goes wrong. Letters are always kept. When the walk reaches the end with nothing open and both budgets used up, the built string is a valid answer. A set removes the duplicates that come from deleting different copies of the same bracket in a row.
- Scan s: '(' → open++. ')' → if open > 0, open--, else right++. Then left = open.
- dfs(i, open, left, right): at the end, record the path if open, left and right are all 0.
- If s[i] is '(' and left > 0, try removing it: dfs(i + 1, open, left - 1, right). Same for ')' with right.
- Then try keeping s[i]: a letter always, '(' with open + 1, ')' only when open > 0, with open - 1. Undo the append afterwards.
- Return the contents of the result set.
class Solution {
private String s;
private Set<String> found = new HashSet<>();
public List<String> removeInvalidParentheses(String s) {
this.s = s;
int open = 0, right = 0;
for (char c : s.toCharArray()) {
if (c == '(') open++;
else if (c == ')') {
if (open > 0) open--;
else right++;
}
}
dfs(0, 0, open, right, new StringBuilder());
return new ArrayList<>(found);
}
private void dfs(int i, int open, int left, int right, StringBuilder path) {
if (i == s.length()) {
if (open == 0 && left == 0 && right == 0) found.add(path.toString());
return;
}
char c = s.charAt(i);
if (c == '(' && left > 0) dfs(i + 1, open, left - 1, right, path);
if (c == ')' && right > 0) dfs(i + 1, open, left, right - 1, path);
path.append(c);
if (c == '(') dfs(i + 1, open + 1, left, right, path);
else if (c != ')') dfs(i + 1, open, left, right, path);
else if (open > 0) dfs(i + 1, open - 1, left, right, path);
path.setLength(path.length() - 1);
}
}class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
open_count = 0
right = 0
for c in s:
if c == "(":
open_count += 1
elif c == ")":
if open_count > 0:
open_count -= 1
else:
right += 1
found = set()
path = []
def dfs(i: int, opened: int, left: int, right: int) -> None:
if i == len(s):
if opened == 0 and left == 0 and right == 0:
found.add("".join(path))
return
c = s[i]
if c == "(" and left > 0:
dfs(i + 1, opened, left - 1, right)
if c == ")" and right > 0:
dfs(i + 1, opened, left, right - 1)
path.append(c)
if c == "(":
dfs(i + 1, opened + 1, left, right)
elif c != ")":
dfs(i + 1, opened, left, right)
elif opened > 0:
dfs(i + 1, opened - 1, left, right)
path.pop()
dfs(0, 0, open_count, right)
return list(found)class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
this->s = s;
int open = 0, right = 0;
for (char c : s) {
if (c == '(') open++;
else if (c == ')') {
if (open > 0) open--;
else right++;
}
}
string path;
dfs(0, 0, open, right, path);
return vector<string>(found.begin(), found.end());
}
private:
string s;
unordered_set<string> found;
void dfs(int i, int open, int left, int right, string& path) {
if (i == (int)s.size()) {
if (open == 0 && left == 0 && right == 0) found.insert(path);
return;
}
char c = s[i];
if (c == '(' && left > 0) dfs(i + 1, open, left - 1, right, path);
if (c == ')' && right > 0) dfs(i + 1, open, left, right - 1, path);
path.push_back(c);
if (c == '(') dfs(i + 1, open + 1, left, right, path);
else if (c != ')') dfs(i + 1, open, left, right, path);
else if (open > 0) dfs(i + 1, open - 1, left, right, path);
path.pop_back();
}
};function removeInvalidParentheses(s) {
let open = 0, right = 0;
for (const c of s) {
if (c === "(") open++;
else if (c === ")") {
if (open > 0) open--;
else right++;
}
}
const found = new Set();
const path = [];
const dfs = (i, opened, left, right) => {
if (i === s.length) {
if (opened === 0 && left === 0 && right === 0) found.add(path.join(""));
return;
}
const c = s[i];
if (c === "(" && left > 0) dfs(i + 1, opened, left - 1, right);
if (c === ")" && right > 0) dfs(i + 1, opened, left, right - 1);
path.push(c);
if (c === "(") dfs(i + 1, opened + 1, left, right);
else if (c !== ")") dfs(i + 1, opened, left, right);
else if (opened > 0) dfs(i + 1, opened - 1, left, right);
path.pop();
};
dfs(0, 0, open, right);
return [...found];
}Edge cases to test
- The string is already valid: return it alone, with zero removals
- No brackets at all: return the string itself
- Every bracket must go: the answer can be just the empty string
- Different removals can produce the same string: each result must appear only once
- Letters are never removed; they can sit anywhere
- Both extra '(' and extra ')' in the same string
Hints
Hint 1
Removing a character from a string gives a shorter string. Think of every string reachable with 1 removal, then with 2, and so on. Which level do you stop at?
Hint 2
Breadth-first search over those levels finds the smallest number of removals first. Use a set so the same string is not explored twice.
Hint 3
You can count in advance exactly how many '(' and how many ')' must go: one left-to-right scan with an open counter. Then backtrack over the string, deciding for each bracket whether to keep it or spend one removal on it, and collect the valid results in a set.
FAQ
What is the best time complexity for Remove Invalid Parentheses?
Optimal (count the removals, then backtrack) runs in O(2^n · n) time and O(n) besides the output extra space. Each of the up to n brackets is either kept or removed, so there are at most 2^n paths, and recording a result costs O(n). The fixed removal budgets and the open check cut most paths early.
Which pattern does Remove Invalid Parentheses use?
It is a recursion & backtracking problem that uses the pick / not-pick pattern. Other problems with the same pattern: Generate all binary strings without consecutive 1's, Subsets (2 choices per element), Subsets II.
Is there a brute force solution for Remove Invalid Parentheses?
Yes. Breadth-first search by number of removals takes O(2^n · n) time and O(2^n · n) space. Level 0 is the string itself.
Which edge cases should I test for Remove Invalid Parentheses?
The string is already valid: return it alone, with zero removals; No brackets at all: return the string itself; Every bracket must go: the answer can be just the empty string; Different removals can produce the same string: each result must appear only once; Letters are never removed; they can sit anywhere; Both extra '(' and extra ')' in the same string.