Tutorialspoint
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)
StringsAlgorithmsAdobeSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Count the number of invalid opening and closing parentheses to understand how many we need to remove.

 Step 2: Use BFS to generate all possible strings with one character removed at each level.
 Step 3: Check if a generated string is valid (balanced parentheses).
 Step 4: Once we find valid strings at a particular level, we stop going deeper as we want minimum removals.
 Step 5: Use a visited set to avoid processing the same string multiple times.
 Step 6: Only try removing parentheses characters, not letters.
 Step 7: Return all valid strings found at the shallowest level of our search.

Submitted Code :