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
BFS Decision Tree for "()())()"Root"()())()"InvalidInvalidInvalidInvalidInvalidContinue to Level 2...ValidValidValidValidValidโœ… Found valid solutions at Level 2!Results: ["()()()", "(())()"] Minimum removals = 2, Stop BFS here๐ŸŽฏ Key Insightsโ€ข BFS explores by removal count (0, 1, 2, ...)โ€ข First level with valid strings = minimumโ€ข No need to explore deeper levelsโ€ข Guarantees optimal solutionTime: O(2^n), Space: O(2^n), but early termination helps!
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
Asked in
Meta 45 Google 38 Amazon 32 Microsoft 28
52.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen