Remove Invalid Parentheses - Problem

Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.

Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.

A valid string has properly matched parentheses where:

  • Every opening parenthesis ( has a corresponding closing parenthesis )
  • The closing parentheses appear after their corresponding opening parentheses

Input & Output

Example 1 — Extra Closing Parenthesis
$ Input: s = "()())"
Output: ["()()", "(())"]
💡 Note: Remove one ')' to get valid strings. Two possibilities: remove the 4th character to get "()()" or remove the 5th character to get "(())"
Example 2 — Multiple Invalid Parentheses
$ Input: s = "((("
Output: [""]
💡 Note: All three opening parentheses are invalid since there are no closing ones. Remove all parentheses to get empty string.
Example 3 — 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 ')'
  • There will be at most 20 parentheses in s

Visualization

Tap to expand
Remove Invalid Parentheses: Find All Valid StringsInput:()())Invalid - extra )Remove 4th char:Remove 5th char:()()(())✓ Valid✓ ValidOutput:["()()", "(())"]
Understanding the Visualization
1
Input
String with invalid parentheses: ()())
2
Process
Find all ways to remove minimum parentheses
3
Output
All valid strings with minimum removals
Key Takeaway
🎯 Key Insight: BFS naturally finds minimum removals first, while backtracking with pre-calculated limits provides efficient pruning
Asked in
Facebook 85 Google 65 Amazon 45 Microsoft 35
125.0K Views
High Frequency
~35 min Avg. Time
3.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