Remove Invalid Parentheses (LeetCode 301): Solution and Explanation

Hard
String
Backtracking
Breadth First Search

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. 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.
  2. Start with queue = [s] and visited = {s}.
  3. For the current level, test every string in queue with isValid and collect the valid ones in result.
  4. If result is not empty, return it immediately, because every string on this level used the minimum number of removals.
  5. 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 in visited.
  6. Replace queue with the next level and repeat. The loop always ends, since the empty string is valid.

Step-by-step example

s = "()())()"
  1. Level 0: the queue is ["()())()"]. The counter goes 1, 0, 1, 0, then -1 at index 4, so the string is invalid and result stays empty.
  2. 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 "()()()".
  3. Removing index 4 also gives "()()()", which is already in visited, so it is skipped. Indices 5 and 6 give "()()))" and "()())(".
  4. Check level 1: "(())()" and "()()()" both pass isValid, while the others fail.
  5. result is 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 [""]

Time and space complexity

Time

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.

Space

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 visited set, 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.