Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Remove Invalid Parentheses

  • Difficulty Level : Hard
  • Last Updated : 16 Jun, 2021

An expression will be given which can contain open and close parentheses and optionally some characters, No other operator will be there in string. We need to remove minimum number of parentheses to make the input string valid. If more than one valid output are possible removing same number of parentheses then print all such output. 
Examples: 
 

Input  : str = “()())()” -
Output : ()()() (())()
There are two possible solutions
"()()()" and "(())()"

Input  : str = (v)())()
Output : (v)()()  (v())()

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

As we need to generate all possible output we will backtrack among all states by removing one opening or closing bracket and check if they are valid if invalid then add the removed bracket back and go for next state. We will use BFS for moving through states, use of BFS will assure removal of minimal number of brackets because we traverse into states level by level and each level corresponds to one extra bracket removal. Other than this BFS involve no recursion so overhead of passing parameters is also saved. 
Below code has a method isValidString to check validity of string, it counts open and closed parenthesis at each index ignoring non-parenthesis character. If at any instant count of close parenthesis becomes more than open then we return false else we keep update the count variable. 
 

C++




/*  C/C++ program to remove invalid parenthesis */
#include <bits/stdc++.h>
using namespace std;
 
//  method checks if character is parenthesis(open
// or closed)
bool isParenthesis(char c)
{
    return ((c == '(') || (c == ')'));
}
 
//  method returns true if string contains valid
// parenthesis
bool isValidString(string str)
{
    int cnt = 0;
    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] == '(')
            cnt++;
        else if (str[i] == ')')
            cnt--;
        if (cnt < 0)
            return false;
    }
    return (cnt == 0);
}
 
//  method to remove invalid parenthesis
void removeInvalidParenthesis(string str)
{
    if (str.empty())
        return ;
 
    //  visit set to ignore already visited string
    set<string> visit;
 
    //  queue to maintain BFS
    queue<string> q;
    string temp;
    bool level;
 
    //  pushing given string as starting node into queue
    q.push(str);
    visit.insert(str);
    while (!q.empty())
    {
        str = q.front();  q.pop();
        if (isValidString(str))
        {
            cout << str << endl;
 
            // If answer is found, make level true
            // so that valid string of only that level
            // are processed.
            level = true;
        }
        if (level)
            continue;
        for (int i = 0; i < str.length(); i++)
        {
            if (!isParenthesis(str[i]))
                continue;
 
            // Removing parenthesis from str and
            // pushing into queue,if not visited already
            temp = str.substr(0, i) + str.substr(i + 1);
            if (visit.find(temp) == visit.end())
            {
                q.push(temp);
                visit.insert(temp);
            }
        }
    }
}
 
//  Driver code to check above methods
int main()
{
    string expression = "()())()";
    removeInvalidParenthesis(expression);
 
    expression = "()v)";
    removeInvalidParenthesis(expression);
 
    return 0;
}

Java




// Java program to remove invalid parenthesis
import java.util.*;
 
class GFG
{
 
// method checks if character is parenthesis(open
// or closed)
static boolean isParenthesis(char c)
{
    return ((c == '(') || (c == ')'));
}
 
// method returns true if string contains valid
// parenthesis
static boolean isValidString(String str)
{
    int cnt = 0;
    for (int i = 0; i < str.length(); i++)
    {
        if (str.charAt(i) == '(')
            cnt++;
        else if (str.charAt(i) == ')')
            cnt--;
        if (cnt < 0)
            return false;
    }
    return (cnt == 0);
}
 
// method to remove invalid parenthesis
static void removeInvalidParenthesis(String str)
{
    if (str.isEmpty())
        return;
 
    // visit set to ignore already visited string
    HashSet<String> visit = new HashSet<String>();
 
    // queue to maintain BFS
    Queue<String> q = new LinkedList<>();
    String temp;
    boolean level = false;
 
    // pushing given string as
    // starting node into queue
    q.add(str);
    visit.add(str);
    while (!q.isEmpty())
    {
        str = q.peek(); q.remove();
        if (isValidString(str))
        {
            System.out.println(str);
 
            // If answer is found, make level true
            // so that valid string of only that level
            // are processed.
            level = true;
        }
        if (level)
            continue;
        for (int i = 0; i < str.length(); i++)
        {
            if (!isParenthesis(str.charAt(i)))
                continue;
 
            // Removing parenthesis from str and
            // pushing into queue,if not visited already
            temp = str.substring(0, i) + str.substring(i + 1);
            if (!visit.contains(temp))
            {
                q.add(temp);
                visit.add(temp);
            }
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
    String expression = "()())()";
    removeInvalidParenthesis(expression);
 
    expression = "()v)";
    removeInvalidParenthesis(expression);
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 program to remove invalid parenthesis
 
# Method checks if character is parenthesis(open
# or closed)
def isParenthesis(c):
    return ((c == '(') or (c == ')'))
 
# method returns true if contains valid
# parenthesis
def isValidString(str):
    cnt = 0
    for i in range(len(str)):
        if (str[i] == '('):
            cnt += 1
        elif (str[i] == ')'):
            cnt -= 1
        if (cnt < 0):
            return False
    return (cnt == 0)
     
# method to remove invalid parenthesis
def removeInvalidParenthesis(str):
    if (len(str) == 0):
        return
         
    # visit set to ignore already visited
    visit = set()
     
    # queue to maintain BFS
    q = []
    temp = 0
    level = 0
     
    # pushing given as starting node into queu
    q.append(str)
    visit.add(str)
    while(len(q)):
        str = q[0]
        q.pop()
        if (isValidString(str)):
            print(str)
             
            # If answer is found, make level true
            # so that valid of only that level
            # are processed.
            level = True
        if (level):
            continue
        for i in range(len(str)):
            if (not isParenthesis(str[i])):
                continue
                 
            # Removing parenthesis from str and
            # pushing into queue,if not visited already
            temp = str[0:i] + str[i + 1:]
            if temp not in visit:
                q.append(temp)
                visit.add(temp)
 
# Driver Code
expression = "()())()"
removeInvalidParenthesis(expression)
expression = "()v)"
removeInvalidParenthesis(expression)
 
# This code is contributed by SHUBHAMSINGH10

C#




// C# program to remove invalid parenthesis
using System;
using System.Collections.Generic;
 
class GFG
{
 
// method checks if character is
// parenthesis(open or closed)
static bool isParenthesis(char c)
{
    return ((c == '(') || (c == ')'));
}
 
// method returns true if string contains
// valid parenthesis
static bool isValidString(String str)
{
    int cnt = 0;
    for (int i = 0; i < str.Length; i++)
    {
        if (str[i] == '(')
            cnt++;
        else if (str[i] == ')')
            cnt--;
        if (cnt < 0)
            return false;
    }
    return (cnt == 0);
}
 
// method to remove invalid parenthesis
static void removeInvalidParenthesis(String str)
{
    if (str == null || str == "")
        return;
 
    // visit set to ignore already visited string
    HashSet<String> visit = new HashSet<String>();
 
    // queue to maintain BFS
    Queue<String> q = new Queue<String>();
    String temp;
    bool level = false;
 
    // pushing given string as
    // starting node into queue
    q.Enqueue(str);
    visit.Add(str);
    while (q.Count != 0)
    {
        str = q.Peek(); q.Dequeue();
        if (isValidString(str))
        {
            Console.WriteLine(str);
 
            // If answer is found, make level true
            // so that valid string of only that level
            // are processed.
            level = true;
        }
         
        if (level)
            continue;
        for (int i = 0; i < str.Length; i++)
        {
            if (!isParenthesis(str[i]))
                continue;
 
            // Removing parenthesis from str and
            // pushing into queue,if not visited already
            temp = str.Substring(0, i) +
                   str.Substring(i + 1);
            if (!visit.Contains(temp))
            {
                q.Enqueue(temp);
                visit.Add(temp);
            }
        }
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    String expression = "()())()";
    removeInvalidParenthesis(expression);
 
    expression = "()v)";
    removeInvalidParenthesis(expression);
}
}
 
// This code is contributed by Princi Singh

Javascript




<script>
 
// JavaScript program to remove invalid parenthesis
 
// method checks if character is parenthesis(open
// or closed)
function isParenthesis(c)
{
    return ((c == '(') || (c == ')'));
}
 
// method returns true if string contains valid
// parenthesis
function isValidString(str)
{
    let cnt = 0;
    for (let i = 0; i < str.length; i++)
    {
        if (str[i] == '(')
            cnt++;
        else if (str[i] == ')')
            cnt--;
        if (cnt < 0)
            return false;
    }
    return (cnt == 0);
}
 
// method to remove invalid parenthesis
function removeInvalidParenthesis(str)
{
    if (str.length==0)
        return;
   
    // visit set to ignore already visited string
    let visit = new Set();
   
    // queue to maintain BFS
    let q = [];
    let temp;
    let level = false;
   
    // pushing given string as
    // starting node into queue
    q.push(str);
    visit.add(str);
    while (q.length!=0)
    {
        str = q.shift();
        if (isValidString(str))
        {
            document.write(str+"<br>");
   
            // If answer is found, make level true
            // so that valid string of only that level
            // are processed.
            level = true;
        }
        if (level)
            continue;
        for (let i = 0; i < str.length; i++)
        {
            if (!isParenthesis(str[i]))
                continue;
   
            // Removing parenthesis from str and
            // pushing into queue,if not visited already
            temp = str.substring(0, i) + str.substring(i + 1);
            if (!visit.has(temp))
            {
                q.push(temp);
                visit.add(temp);
            }
        }
    }
}
 
// Driver Code
let expression = "()())()";
removeInvalidParenthesis(expression);
 
expression = "()v)";
removeInvalidParenthesis(expression);
 
// This code is contributed by rag2127
 
</script>

Output:  

(())()
()()()
(v)
()v

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!