Tutorialspoint
Problem
Solution
Submissions

Invalid Parentheses

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to remove the minimum number of invalid parentheses to make the input string valid. Return all possible valid expressions. A valid expression should have properly matched parentheses with each opening parenthesis '(' having a corresponding closing parenthesis ')' and they should be in correct order.

Example 1
  • Input: s = "()())"
  • Output: ["()()", "(())"]
  • Explanation: Step 1: Input has 3 opening and 3 closing parentheses, but one extra closing Step 2: Remove one closing parenthesis to make it valid Step 3: Two possibilities: remove 3rd ')' → "()()" or remove 5th ')' → "(())" Step 4: Both results are valid expressions
Example 2
  • Input: s = "((("
  • Output: [""]
  • Explanation: Step 1: Input has 3 opening parentheses with no closing ones Step 2: All opening parentheses must be removed to make it valid Step 3: Only empty string remains as valid expression Step 4: Therefore, output is [""]
Constraints
  • 1 <= s.length <= 25
  • s consists of lowercase English letters and parentheses '(' and ')'
  • There will be at most 20 parentheses in s
  • Time Complexity: O(2^n) where n is number of parentheses
  • Space Complexity: O(n) for recursion stack
StringsBacktracking Goldman SachsArctwist
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 backtracking to try removing different combinations of parentheses
  • For each position, decide whether to keep or remove the parenthesis
  • Check validity of expression by counting balanced parentheses
  • Use a set or duplicate checking to avoid returning duplicate results
  • Prune branches early if removing more parentheses than needed

Steps to solve by this approach:

 Step 1: Count the number of invalid opening and closing parentheses that need to be removed
 Step 2: Use backtracking to explore all possible combinations of removing parentheses
 Step 3: At each position, decide whether to keep or remove the current character
 Step 4: Track the count of opening and closing parentheses to ensure balance
 Step 5: When reaching the end of string, check if all invalid parentheses are removed and expression is balanced
 Step 6: Store valid expressions while avoiding duplicates
 Step 7: Return all unique valid expressions found through backtracking

Submitted Code :