Remove Invalid Parentheses - Problem
Remove Invalid Parentheses is a challenging string manipulation problem that tests your ability to find all valid solutions with minimal modifications.
Given a string s containing parentheses '(', ')' and letters, your task is to remove the minimum number of invalid parentheses to make the string valid. A valid string has properly matched and nested parentheses.
Key Requirements:
- Remove the minimum number of parentheses
- Return all unique valid strings possible
- Letters can appear anywhere and should be preserved
- Order of results doesn't matter
Example: "()())()" โ ["()()()", "(())()"]
Both results remove exactly 1 parenthesis and create valid strings.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "()())()"
โบ
Output:
["()()()", "(())()"]
๐ก Note:
Remove the extra ')' at index 4. Two ways to form valid strings: remove it to get "()()()" or rearrange logic to see "(())()" is also possible with different removal.
example_2.py โ Multiple Removals
$
Input:
s = "((("
โบ
Output:
[""]
๐ก Note:
All parentheses are invalid '(' with no matching ')'. Must remove all 3 characters to get empty string, which is valid.
example_3.py โ Already Valid
$
Input:
s = "()"
โบ
Output:
["()"]
๐ก Note:
String is already valid, no removals needed. Return the original string.
Constraints
- 1 โค s.length โค 25
-
s consists of lowercase English letters and parentheses
'('and')' - The input string may contain letters that should be preserved
- Return results in any order
Visualization
Tap to expand
Understanding the Visualization
1
Start Root
Begin with original string at root
2
Level 1
Try removing each parenthesis (one removal)
3
Check Validity
Test if any strings at current level are valid
4
Stop or Continue
If valid found, return results; else go deeper
Key Takeaway
๐ฏ Key Insight: BFS naturally finds minimum removals first, making it the optimal approach for this problem
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code