Python 0301.py
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
# breadth-first search
todo = [ s ]
stop = False # becomes True after first valid string found
while not stop:
next = set()
for t in todo:
# check if brackets match
depth = 0
for c in t:
if c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth < 0: # "underflow"
break
# we have a match, stop after this round
if depth == 0:
stop = True
yield t
continue
# keep going ...
for i, c in enumerate(t):
if c in "()": # always keep letters, remove only parentheses
shorter = t[: i] + t[i + 1:]
next.add(shorter)
todo = next
Difficulty
and has an acceptance rate of about 50% (1+ million submissions).
Typical patterns to solve this problem:
- Backtracking
- Breadth First Search
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “remove invalid parentheses” problem by performing a breadth-first search (BFS) over progressively shorter candidate strings. Starting from the original input, it explores all strings that can be obtained by deleting a single parenthesis at each step. The search stops as soon as any string at the current BFS depth is found to be valid; all valid strings discovered at that depth are yielded. This guarantees that the returned results contain the minimum number of deletions required to obtain a balanced parenthesis sequence.
Core Algorithm
Initialization
todo = [s] # current frontier of candidates
stop = False # becomes True after the first valid level is found
The algorithm begins with a list containing only the original string. The stop flag controls the outer loop, ensuring that once a valid level is reached, no deeper (and therefore more costly) levels are explored.
BFS Loop
while not stop:
next = set() # collect unique candidates for the next level
for t in todo:
# validity test and generation of children
...
todo = next
The outer while loop iterates level by level. The next container is a set, which automatically removes duplicate strings that may arise from different deletion paths leading to the same result.
Validity Test
depth = 0
for c in t:
if c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth < 0: # early exit on underflow
break
if depth == 0: # balanced parentheses
stop = True
yield t
continue
A single pass computes the net balance of opening and closing parentheses. The moment the balance becomes negative, the loop aborts because the string cannot be valid regardless of later characters. If the final depth equals zero, the string is balanced, the stop flag is set, and the string is emitted via yield. The continue statement skips the generation of shorter strings for this already-valid candidate.
Generation of Shorter Candidates
for i, c in enumerate(t):
if c in "()": # only parentheses are removable
shorter = t[:i] + t[i+1:]
next.add(shorter)
For each character that is a parenthesis, a new string is formed by omitting that character. The resulting string is added to the next set, ensuring that each distinct deletion is considered exactly once per level.
Edge Cases Handled
When the input string contains no parentheses, the validity loop never modifies depth, leaving it at zero. Consequently, the original string is yielded immediately, and the algorithm terminates without generating any shorter strings.
If the input consists solely of mismatched parentheses, the BFS proceeds to delete characters until a balanced configuration emerges. Because the search stops at the first level that yields a balanced string, the algorithm automatically returns the minimal-deletion solutions even for heavily corrupted inputs.
An empty input string is treated as a valid balanced string. The initial todo list contains the empty string, the validity loop finishes with depth == 0, and the empty string is yielded as the sole result.
Strings that become valid after removing characters from the middle, the beginning, or the end are all reachable because the generation step iterates over every parenthesis position. The use of a set prevents duplicate entries when different deletion orders lead to the same shorter string.
Performance Optimizations
The early-exit condition inside the validity check (if depth < 0: break) prevents unnecessary scanning of the remainder of a string once an imbalance is detected. This reduces the amount of work for strings that are clearly invalid early in the sequence.
Storing the next frontier in a set eliminates redundant processing of identical strings that could be produced by multiple deletion paths. This deduplication dramatically cuts down the number of candidates examined in deeper BFS levels.
The stop flag ensures that the algorithm halts after the first level containing any valid strings. Since BFS explores candidates in order of increasing deletions, this guarantees that only the minimal-deletion solutions are generated, avoiding the exponential blow-up that would occur if the search continued to explore deeper levels.
Yielding results lazily with yield allows the caller to consume valid strings as they are found without constructing a full list in memory. This streaming approach reduces peak memory usage, especially when the number of valid solutions is large.
ELI5 - Simplified Explanation
Imagine a big box of blocks that has letters and some brackets mixed inside. Some of the brackets are happy because they have a matching partner, but some are lonely and do not fit correctly.
The instructions start by putting the whole string into a list to look at. Then, the code starts a loop that keeps going until it finds a way to make all the brackets match perfectly. Inside this loop, it checks every string in the list. During the check, a imaginary number counter goes up when it sees an opening bracket and down when it sees a closing bracket. If the number ever drops below zero, it means a closing bracket appeared before an opening one, and that cannot be right.
If the number ends at zero, all the brackets are perfectly balanced. That string is a success. If the brackets are not balanced, the code tries to fix it by taking out one bracket at a time. It makes new versions of the string with one bracket missing and puts them into a new pile. Once the code finds strings where all the brackets match, it saves them and stops looking for smaller versions.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | aylei | Rust | ||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 20: Valid Parentheses
- problem 1963: Minimum Number of Swaps to Make the String Balanced
Solved On The Same Day
- problem 558: Logical OR of Two Binary Grids Represented as Quad-Trees
- problem 592: Fraction Addition and Subtraction
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality