Remove Invalid Parentheses (LeetCode 301): Solution and Explanation
Given a string of parentheses mixed with letters, delete as few parentheses as possible so the string becomes balanced. Return every distinct balanced string you can reach with that minimum number of deletions.
Watch it run step by step
Try your own input and write the code →Intuition
The key word is minimum. We want all valid strings that are reachable by removing exactly the smallest possible number of characters, and nothing that needed one more removal. That is a shortest path question: the original string is the start node, removing a single parenthesis is one edge, and the goal is any valid string. Breadth-first search explores strings in order of how many characters were removed, so the first level that contains a valid string is exactly the minimum.
A brute force that generates every subsequence and keeps the valid ones with maximum length works, but it always enumerates all 2^n subsets. BFS can stop early. If the input only needs one removal, we generate at most n strings at level one, find the valid ones, and return without ever touching deeper levels.
Two details make BFS practical. First, many different removal orders produce the same string (removing either of two adjacent ) gives the same result), so a visited set keeps each string from being enqueued twice. Second, validity is cheap to test with a running counter: add one for (, subtract one for ), fail if it ever goes negative, and require it to end at zero. Letters are ignored by the counter and are never removed.
Approach: Breadth-first search by number of removals
- Write
isValid, which scans the string with a counter, returns false if the counter drops below zero and returns true only if it ends at zero. - Start with
queue = [s]andvisited = {s}. - For the current level, test every string in
queuewithisValidand collect the valid ones inresult. - If
resultis not empty, return it immediately, because every string on this level used the minimum number of removals. - Otherwise build the next level: for each string and each index holding
(or), remove that character and enqueue the new string if it is not already invisited. - Replace
queuewith the next level and repeat. The loop always ends, since the empty string is valid.
Step-by-step example
s = "()())()"
- Level 0: the queue is ["()())()"]. The counter goes 1, 0, 1, 0, then -1 at index 4, so the string is invalid and
resultstays empty. - Build level 1 by removing one parenthesis at each index 0 through 6. Removing index 0 gives ")())()", index 1 gives "(())()", index 2 gives "()))()", index 3 gives "()()()".
- Removing index 4 also gives "()()()", which is already in
visited, so it is skipped. Indices 5 and 6 give "()()))" and "()())(". - Check level 1: "(())()" and "()()()" both pass
isValid, while the others fail. resultis non-empty, so return ["(())()", "()()()"] without exploring level 2.
Code: Python, Java, C++
1class Solution:
2 def removeInvalidParentheses(self, s: str) -> List[str]:
3 def isValid(string):
4 count = 0
5 for c in string:
6 if c == '(':
7 count += 1
8 elif c == ')':
9 count -= 1
10 if count < 0:
11 return False
12 return count == 0
13
14 result = []
15 visited = {s}
16 queue = [s]
17
18 while queue:
19 for curr in queue:
20 if isValid(curr):
21 result.append(curr)
22
23 if result:
24 return result
25
26 nextQueue = []
27 for curr in queue:
28 for i in range(len(curr)):
29 if curr[i] in '()':
30 nextStr = curr[:i] + curr[i+1:]
31 if nextStr not in visited:
32 visited.add(nextStr)
33 nextQueue.append(nextStr)
34 queue = nextQueue
35
36 return [""]1class Solution {
2 public List<String> removeInvalidParentheses(String s) {
3 List<String> result = new ArrayList<>();
4 Set<String> visited = new HashSet<>();
5 Queue<String> queue = new LinkedList<>();
6
7 queue.offer(s);
8 visited.add(s);
9
10 while (!queue.isEmpty()) {
11 int size = queue.size();
12 List<String> currLevel = new ArrayList<>();
13 for (int i = 0; i < size; i++) {
14 String curr = queue.poll();
15 currLevel.add(curr);
16 if (isValid(curr)) result.add(curr);
17 }
18
19 if (!result.isEmpty()) return result;
20
21 for (String curr : currLevel) {
22 for (int i = 0; i < curr.length(); i++) {
23 char c = curr.charAt(i);
24 if (c == '(' || c == ')') {
25 String next = curr.substring(0, i) + curr.substring(i + 1);
26 if (!visited.contains(next)) {
27 visited.add(next);
28 queue.offer(next);
29 }
30 }
31 }
32 }
33 }
34
35 return Arrays.asList("");
36 }
37
38 private boolean isValid(String s) {
39 int count = 0;
40 for (char c : s.toCharArray()) {
41 if (c == '(') count++;
42 else if (c == ')') count--;
43 if (count < 0) return false;
44 }
45 return count == 0;
46 }
47}1class Solution {
2public:
3 vector<string> removeInvalidParentheses(string s) {
4 auto isValid = [](const string& str) {
5 int count = 0;
6 for (char c : str) {
7 if (c == '(') count++;
8 else if (c == ')') count--;
9 if (count < 0) return false;
10 }
11 return count == 0;
12 };
13
14 vector<string> result;
15 unordered_set<string> visited;
16 queue<string> q;
17
18 q.push(s);
19 visited.insert(s);
20
21 while (!q.empty()) {
22 int size = q.size();
23 vector<string> currLevel;
24 for (int i = 0; i < size; i++) {
25 string curr = q.front();
26 q.pop();
27 currLevel.push_back(curr);
28 if (isValid(curr)) result.push_back(curr);
29 }
30
31 if (!result.empty()) return result;
32
33 for (const string& curr : currLevel) {
34 for (int i = 0; i < curr.size(); i++) {
35 if (curr[i] == '(' || curr[i] == ')') {
36 string next = curr.substr(0, i) + curr.substr(i + 1);
37 if (!visited.count(next)) {
38 visited.insert(next);
39 q.push(next);
40 }
41 }
42 }
43 }
44 }
45
46 return {""};
47 }
48};Time and space complexity
O(n × 2^n)
In the worst case BFS visits a large fraction of the 2^n subsequences, and each one costs O(n) to build by slicing and O(n) to validate. In practice the search stops at the first valid level, which is usually shallow.
O(n × 2^n)
The visited set and the queue can hold exponentially many strings of length up to n in the worst case.
Other approaches
DFS with removal counts (time O(2^n), space O(n))
First scan to count how many ( and ) must be removed. Then backtrack, removing only those counts and skipping consecutive duplicate characters to avoid repeated results. It prunes far more aggressively than BFS and uses only O(n) stack space beyond the output.
Common mistakes
- Continuing to the next BFS level after finding valid strings, which adds answers that removed more characters than necessary.
- Forgetting the
visitedset, which lets the same string be generated many times and causes both duplicate answers and an explosion in runtime. - Removing letters as well as parentheses, which creates invalid answers since letters must stay in place.
- Checking validity with only a final count of zero, missing strings like ")(" whose running count dips below zero.
Frequently asked questions
Why does BFS guarantee the minimum number of removals?
Level d of the search holds exactly the strings produced by d removals. Because BFS finishes a whole level before moving on, the first level with a valid string is the smallest number of deletions that can work.
What is returned when no parentheses can be kept?
The search keeps removing until it reaches strings with no parentheses at all, which are always valid. For an input like ")(" that means the answer is [""].
BFS or DFS for Remove Invalid Parentheses?
BFS is simpler to reason about because minimality falls out of the level order. DFS with precomputed removal counts is faster and lighter on memory, but you have to handle duplicate pruning carefully.