
Problem
Solution
Submissions
Remove Invalid Parentheses
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to remove the minimum number of invalid parentheses to make the input string valid. Return all possible results. The input string may contain letters other than the parentheses '(' and ')'.
Example 1
- Input: s = "()())()"
- Output: ["()()()", "(())()"]
- Explanation: Step 1: The string "()())()" has one extra closing parenthesis. Step 2: We need to remove exactly one parenthesis to make it valid. Step 3: Removing the first closing parenthesis gives "()()()" which is valid. Step 4: Removing the second closing parenthesis gives "(())()" which is valid. Step 5: Both are minimal removals, so both are included in the output.
Example 2
- Input: s = "(a)())()"
- Output: ["(a)()()", "(a())()"]
- Explanation: Step 1: The string "(a)())()" has one extra closing parenthesis. Step 2: We need to remove exactly one parenthesis to make it valid. Step 3: Removing the first closing parenthesis gives "(a)()()" which is valid. Step 4: Removing the second closing parenthesis gives "(a())()" which is valid. Step 5: Both are minimal removals, so both are included in the output.
Constraints
- 1 <= s.length <= 25
- s consists of lowercase English letters and parentheses '(' and ')'.
- There will be at most 20 parentheses in the input string.
- Time Complexity: O(2^n) where n is the length of the string
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Count the number of invalid opening and closing parentheses.
- Use breadth-first search (BFS) or depth-first search (DFS) to try removing each parenthesis.
- Use a set to avoid duplicate results.
- For each candidate string, check if it's valid before adding to results.
- A string is valid if the count of opening and closing parentheses is balanced.