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 - BFS Approach INPUT Input String s: ( ) ( ) ) 0 1 2 3 4 Extra ')' at index 4 Problem: Remove minimum invalid parentheses to make valid Input: s = "()())" Unbalanced: 1 extra ')' Min removals needed: 1 ALGORITHM (BFS) 1 Initialize BFS Queue Add original string to queue L0: "()())" 2 Check Validity If valid, add to result 3 Generate Candidates Remove one char at a time L1: "()()" "(())" ")()" Valid found! Stop expanding. 4 Use Set for Dedup Avoid duplicate strings Visited: {seen strings...} Prevents revisiting FINAL RESULT Valid Strings Found: "()()" OK - Balanced "(())" OK - Balanced Output: ["()()", "(())"] Minimum Removals: 1 2 unique valid strings Key Insight: BFS guarantees minimum removals by exploring level-by-level. Each level represents one more removal. Once we find valid strings at a level, we stop expanding further. Use a HashSet to avoid duplicates. Time: O(n * 2^n) | Space: O(2^n) for storing all possible substrings in the queue. TutorialsPoint - Remove Invalid Parentheses | BFS Approach
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