Remove Invalid Parentheses

Last Updated : 4 May, 2026

Given a string str consisting only of lowercase letters and the characters '(' and ')'. Your task is to delete minimum parentheses so that the resulting string is balanced, i.e., every opening parenthesis has a matching closing parenthesis in the correct order, and no extra closing parentheses appear.

Return all distinct strings you can obtain by performing the minimum number of removals.

Examples:

Input: str = "()())()"
Output: "()()()" "(())()"
Explanation: We can remove the closing bracket at index 3 to obtain the balanced string "()()()". Similarly, we can remove the closing bracket at index 1 to obtain the balanced string "(())()".

Input: str = "(v)())()"
Output: "(v)()()" "(v())()"
Explanation: The given string is the modified version of first string containing a letter 'v' . As the letters do not differ the parentheses, the solution remains the same. 

Input: S = ")("
Output: ""

Try It Yourself
redirect icon

Using Breadth First Search (BFS) - O(2 ^ n) Time and O(2 ^ n) Space

The idea is to remove brackets one by one and check for balance. To remove brackets in a systematic way, we use BFS order. We remove one bracket at a time, check for balance, then remove more brackets and again check in BFS manner. We stop when we find a balanced string.

One important observation about this problem is, we can check the balancing by simply counting opening and closing brackets because we have only one type of brackets. We do not need to use stack to check.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if a given string has valid parentheses
bool isValid(string s)
{
    int count = 0;

    for (char c : s)
    {
        // Increment for opening bracket
        if (c == '(')
            count++;

        // Decrement for closing bracket
        else if (c == ')')
        {
            count--;

            // If at any point count becomes negative,
            // more ')' than '(' means invalid string
            if (count < 0)
                return false;
        }
    }

    // Valid only if all '(' are matched
    return count == 0;
}

// Function to generate all valid strings by removing minimum parentheses
vector<string> validParenthesis(string s)
{

    unordered_set<string> visited;
    queue<string> q;
    vector<string> result;

    q.push(s);
    visited.insert(s);

    bool found = false;

    while (!q.empty())
    {

        string curr = q.front();
        q.pop();

        // Check if current string is valid
        if (isValid(curr))
        {
            result.push_back(curr);
            found = true;
        }

        // If valid string found at this level,
        // do not generate next level this ensures minimum removals
        if (found)
            continue;

        // Generate all possible strings by removing one parenthesis
        for (int i = 0; i < curr.length(); i++)
        {

            // Skip non-parenthesis characters
            if (curr[i] != '(' && curr[i] != ')')
                continue;

            // Remove character at index i
            string next = curr.substr(0, i) + curr.substr(i + 1);

            // Add new string if not already visited
            if (visited.find(next) == visited.end())
            {
                visited.insert(next);
                q.push(next);
            }
        }
    }

    return result;
}

int main()
{

    string s = "())(()";

    // Get all valid strings
    vector<string> res = validParenthesis(s);

    // Print result
    for (auto &str : res)
        cout << str << endl;

    return 0;
}
Java
import java.util.*;

public class GFG {

    // Function to check if a given string has valid
    // parentheses
    public static boolean isValid(String s)
    {
        int count = 0;

        for (char c : s.toCharArray()) {

            // Increment for opening bracket
            if (c == '(')
                count++;

            // Decrement for closing bracket
            else if (c == ')') {
                count--;

                // If at any point count becomes negative,
                // more ')' than '(' means invalid string
                if (count < 0)
                    return false;
            }
        }

        // Valid only if all '(' are matched
        return count == 0;
    }

    // Function to generate all valid strings by removing
    // minimum parentheses
    public static List<String> validParenthesis(String s)
    {

        Set<String> visited = new HashSet<>();
        Queue<String> q = new LinkedList<>();
        List<String> result = new ArrayList<>();

        q.add(s);
        visited.add(s);

        boolean found = false;

        while (!q.isEmpty()) {

            String curr = q.poll();

            // Check if current string is valid
            if (isValid(curr)) {
                result.add(curr);
                found = true;
            }

            // If valid string found at this level,
            // do not generate next level this ensures
            // minimum removals
            if (found)
                continue;

            // Generate all possible strings by removing one
            // parenthesis
            for (int i = 0; i < curr.length(); i++) {

                // Skip non-parenthesis characters
                if (curr.charAt(i) != '('
                    && curr.charAt(i) != ')')
                    continue;

                // Remove character at index i
                String next = curr.substring(0, i)
                              + curr.substring(i + 1);

                // Add new string if not already visited
                if (!visited.contains(next)) {
                    visited.add(next);
                    q.add(next);
                }
            }
        }

        return result;
    }

    public static void main(String[] args)
    {

        String s = "()())()";

        // Get all valid strings
        List<String> res = validParenthesis(s);

        // Print result
        for (String str : res)
            System.out.println(str);
    }
}
Python
from collections import deque

# Function to check if a given string has valid parentheses


def isValid(s):
    count = 0

    for c in s:

        # Increment for opening bracket
        if c == '(':
            count += 1

        # Decrement for closing bracket
        elif c == ')':
            count -= 1

            # If at any point count becomes negative,
            # more ')' than '(' means invalid string
            if count < 0:
                return False

    # Valid only if all '(' are matched
    return count == 0


# Function to generate all valid strings by removing minimum parentheses
def validParenthesis(s):

    visited = set()
    q = deque()
    result = []

    q.append(s)
    visited.add(s)

    found = False

    while q:

        curr = q.popleft()

        # Check if current string is valid
        if isValid(curr):
            result.append(curr)
            found = True

        # If valid string found at this level,
        # do not generate next level this ensures minimum removals
        if found:
            continue

        # Generate all possible strings by removing one parenthesis
        for i in range(len(curr)):

            # Skip non-parenthesis characters
            if curr[i] != '(' and curr[i] != ')':
                continue

            # Remove character at index i
            next_str = curr[:i] + curr[i + 1:]

            # Add new string if not already visited
            if next_str not in visited:
                visited.add(next_str)
                q.append(next_str)

    return result


if __name__ == "__main__":
    s = "()())()"

    # Get all valid strings
    res = validParenthesis(s)

    # Print result
    for string in res:
        print(string)
C#
using System;
using System.Collections.Generic;

class GFG {
    // Function to check if a given string has valid
    // parentheses
    public bool IsValid(string s)
    {
        int count = 0;

        foreach(char c in s)
        {
            // Increment for opening bracket
            if (c == '(')
                count++;

            // Decrement for closing bracket
            else if (c == ')') {
                count--;

                // If at any point count becomes negative,
                // more ')' than '(' means invalid string
                if (count < 0)
                    return false;
            }
        }

        // Valid only if all '(' are matched
        return count == 0;
    }

    // Function to generate all valid strings by removing
    // minimum parentheses
    public List<string> validParenthesis(string s)
    {
        HashSet<string> visited = new HashSet<string>();
        Queue<string> q = new Queue<string>();
        List<string> result = new List<string>();

        q.Enqueue(s);
        visited.Add(s);

        bool found = false;

        while (q.Count > 0) {
            string curr = q.Dequeue();

            // Check if current string is valid
            if (IsValid(curr)) {
                result.Add(curr);
                found = true;
            }

            // If valid string found at this level,
            // do not generate next level this ensures
            // minimum removals
            if (found)
                continue;

            // Generate all possible strings by removing one
            // parenthesis
            for (int i = 0; i < curr.Length; i++) {
                // Skip non-parenthesis characters
                if (curr[i] != '(' && curr[i] != ')')
                    continue;

                // Remove character at index i
                string next = curr.Substring(0, i)
                              + curr.Substring(i + 1);

                // Add new string if not already visited
                if (!visited.Contains(next)) {
                    visited.Add(next);
                    q.Enqueue(next);
                }
            }
        }

        return result;
    }

    public static void Main()
    {
        string s = "()())()";

        // Get all valid strings
        List<string> res = validParenthesis(s);

        // Print result
        foreach(string str in res) Console.WriteLine(str);
    }
}
JavaScript
// Function to check if a given string has valid parentheses
function isValid(s)
{
    let count = 0;

    for (let c of s) {

        // Increment for opening bracket
        if (c === "(")
            count++;

        // Decrement for closing bracket
        else if (c === ")") {
            count--;

            // If at any point count becomes negative,
            // more ')' than '(' means invalid string
            if (count < 0)
                return false;
        }
    }

    // Valid only if all '(' are matched
    return count === 0;
}

// Function to generate all valid strings by removing
// minimum parentheses
function validParenthesis(s)
{

    let visited = new Set();
    let q = [];
    let result = [];

    q.push(s);
    visited.add(s);

    let found = false;

    while (q.length > 0) {

        let curr = q.shift();

        // Check if current string is valid
        if (isValid(curr)) {
            result.push(curr);
            found = true;
        }

        // If valid string found at this level,
        // do not generate next level this ensures minimum
        // removals
        if (found)
            continue;

        // Generate all possible strings by removing one
        // parenthesis
        for (let i = 0; i < curr.length; i++) {

            // Skip non-parenthesis characters
            if (curr[i] !== "(" && curr[i] !== ")")
                continue;

            // Remove character at index i
            let next = curr.slice(0, i) + curr.slice(i + 1);

            // Add new string if not already visited
            if (!visited.has(next)) {
                visited.add(next);
                q.push(next);
            }
        }
    }

    return result;
}

// Driver code
let s = "()())()";

// Get all valid strings
let res = validParenthesis(s);

// Print result
for (let str of res)
    console.log(str);

Output
(())()
()()()

Using Depth First Search (DFS) - O(2 ^ n) Time and O(2 ^ n) Space

We first determine how many opening ( and closing ) parentheses are invalid and need to be removed. Then, use a recursive function to explore all ways of removing these parentheses while maintaining balance between open and close brackets. At each step, either skip a parenthesis (if it's invalid) or include it in the current string (if it helps form a valid expression), and continue building the string. Only strings that end with no unmatched parentheses are collected as valid results.

Step-by-step approach to process '())(':

  1. Count invalid parentheses in '())(' gives invalid open = 1 and invalid close = 1
  2. Start recursion at index 0 with open = 1, close = 1, pair = 0 and cur = ""
  3. At index 0 '(' choose skip making open = 0 or include making pair = 1 and cur = "("
  4. From skip path at index 1 ')' choose skip making close = 0, cannot include since pair = 0
  5. Continue to index 2 ')' cannot include and skip not allowed so this path is discarded
  6. From include path at index 0 go to index 1 ')' choose include making pair = 0 and cur = "()" or skip making close = 0
  7. From include case go to index 2 ')' cannot include since pair = 0 so skip making close = 0
  8. Move to index 3 '(' choose skip making open = 0 or include making pair = 1
  9. From skip case reach end with open = 0, close = 0, pair = 0 so add "()" to result
  10. From include case reach end with pair = 1 so discard

Final result is ["()"]

C++
#include <bits/stdc++.h>
using namespace std;

// recursive function to find all valid strings
void findValid(string str, int index, int open, int close, int pair, string cur, vector<string> &res,
               unordered_set<string> &st)
{
    // base case, if end of string is reached
    if (index == str.size())
    {

        // check if all open and closed invalid
        // parenthesis are removed and no pair is left
        if (open == 0 && close == 0 && pair == 0)
        {
            // check if cur is present in the set
            if (st.find(cur) == st.end())
            {
                res.push_back(cur);
                st.insert(cur);
            }
        }
        return;
    }

    // if the current character is not a parenthesis
    if (str[index] != '(' && str[index] != ')')
    {
        // add the character to the current string
        findValid(str, index + 1, open, close, pair, cur + str[index], res, st);
    }
    else
    {
        // if the current character is an open bracket
        if (str[index] == '(')
        {
            // reduce open count by 1,
            // and skip current character
            if (open > 0)
            {
                findValid(str, index + 1, open - 1, close, pair, cur, res, st);
            }

            // add the current character to the string
            findValid(str, index + 1, open, close, pair + 1, cur + str[index], res, st);
        }

        // else if the current character is a closed bracket
        else
        {
            // skip current character and
            // reduce closed count by 1
            if (close > 0)
                findValid(str, index + 1, open, close - 1, pair, cur, res, st);

            // if there is an open pair, reduce
            // it and add the current character
            if (pair > 0)
                findValid(str, index + 1, open, close, pair - 1, cur + str[index], res, st);
        }
    }
}

vector<string> validParenthesis(string &str)
{
    vector<string> result;
    unordered_set<string> st;

    // to store count of invalid
    // open and closed paraenthesis
    int open = 0, close = 0;

    for (auto c : str)
    {
        // if open bracket, increase
        // open invalid count by 1
        if (c == '(')
            open++;

        if (c == ')')
        {
            // decrement invalid open
            // count by 1 if open is not 0
            if (open != 0)
                open--;

            // else increment invalid close
            // bracket count by 1
            else
                close++;
        }
    }

    // recursive function to find all valid strings
    findValid(str, 0, open, close, 0, "", result, st);

    vector<string> res(result.begin(), result.end());
    return res;
}

int main()
{
    string str = "()())()";

    vector<string> res = validParenthesis(str);

    for (auto &s : res)
        cout << s << endl;

    return 0;
}
Java
import java.util.*;

class GFG {

    // recursive function to find all valid strings
    static void findValid(String str, int index, int open,
                          int close, int pair, String cur,
                          List<String> res, Set<String> st)
    {
        // base case, if end of string is reached
        if (index == str.length()) {

            // check if all open and closed invalid
            // parenthesis are removed and no pair is left
            if (open == 0 && close == 0 && pair == 0) {

                // check if cur is present in the set
                if (!st.contains(cur)) {
                    res.add(cur);
                    st.add(cur);
                }
            }
            return;
        }

        // if the current character is not a parenthesis
        if (str.charAt(index) != '('
            && str.charAt(index) != ')') {

            // add the character to the current string
            findValid(str, index + 1, open, close, pair,
                      cur + str.charAt(index), res, st);
        }
        else {

            // if the current character is an open bracket
            if (str.charAt(index) == '(') {

                // reduce open count by 1,
                // and skip current character
                if (open > 0) {
                    findValid(str, index + 1, open - 1,
                              close, pair, cur, res, st);
                }

                // add the current character to the string
                findValid(str, index + 1, open, close,
                          pair + 1, cur + str.charAt(index),
                          res, st);
            }

            // else if the current character is a closed
            // bracket
            else {

                // skip current character and
                // reduce closed count by 1
                if (close > 0)
                    findValid(str, index + 1, open,
                              close - 1, pair, cur, res,
                              st);

                // if there is an open pair, reduce
                // it and add the current character
                if (pair > 0)
                    findValid(str, index + 1, open, close,
                              pair - 1,
                              cur + str.charAt(index), res,
                              st);
            }
        }
    }

    static List<String> validParenthesis(String str)
    {

        List<String> result = new ArrayList<>();
        Set<String> st = new HashSet<>();

        // to store count of invalid
        // open and closed paraenthesis
        int open = 0, close = 0;
        
        for (char c : str.toCharArray()) {
            
            // if open bracket, increase
            // open invalid count by 1
            if (c == '(')
                open++;
            else if (c == ')') {
                
                // decrement invalid open
                // count by 1 if open is not 0
                if (open != 0)
                    open--;
                    
                // else increment invalid close
                // bracket count by 1
                else
                    close++;
            }
        }

        // recursive function to find all valid strings
        findValid(str, 0, open, close, 0, "", result, st);
        return result;
    }

    public static void main(String[] args)
    {
        String str = "()())()";
        List<String> res = validParenthesis(str);

        for (String s : res)
            System.out.println(s);
    }
}
Python
# recursive function to find all valid strings
def findValid(str_, index, open_, close, pair, cur, res, st):

    # base case, if end of string is reached
    if index == len(str_):

        # check if all open and closed invalid
        # parenthesis are removed and no pair is left
        if open_ == 0 and close == 0 and pair == 0:

            # check if cur is present in the set
            if cur not in st:
                res.append(cur)
                st.add(cur)
        return

    # if the current character is not a parenthesis
    if str_[index] not in '()':
        
        # add the character to the current string
        findValid(str_, index + 1, open_, close, pair,
                  cur + str_[index], res, st)

    else:
        
        # if the current character is an open bracket
        if str_[index] == '(':

            # reduce open count by 1,
            # and skip current character
            if open_ > 0:
                findValid(str_, index + 1, open_ - 1,
                          close, pair, cur, res, st)

            # add the current character to the string
            findValid(str_, index + 1, open_, close, pair + 1,
                      cur + str_[index], res, st)

        # else if the current character is a closed bracket
        else:
            
            # skip current character and
            # reduce closed count by 1
            if close > 0:
                findValid(str_, index + 1, open_,
                          close - 1, pair, cur, res, st)

            # if there is an open pair, reduce
            # it and add the current character
            if pair > 0:
                findValid(str_, index + 1, open_, close, pair - 1,
                          cur + str_[index], res, st)


def validParenthesis(str_):
    res = []
    st = set()

    # to store count of invalid
    # open and closed paraenthesis
    open_ = close = 0

    for c in str_:
        
        # if open bracket, increase
        # open invalid count by 1
        if c == '(':
            open_ += 1
        elif c == ')':
            
            # decrement invalid open
            # count by 1 if open is not 0
            if open_ != 0:
                open_ -= 1
                
            # else increment invalid close
            # bracket count by 1
            else:
                close += 1

    # recursive function to find all valid strings
    findValid(str_, 0, open_, close, 0, "", res, st)
    return res


if __name__ == "__main__":
    s = "()())()"
    res = validParenthesis(s)
    
    for string in res:
        print(string)
C#
using System;
using System.Collections.Generic;

class GFG {
    // recursive function to find all valid strings
    public void findValid(string str, int index, int open,
                          int close, int pair, string cur,
                          List<string> res,
                          HashSet<string> st)
    {
        // base case, if end of string is reached
        if (index == str.Length) {
            
            // check if all open and closed invalid
            // parenthesis are removed and no pair is left
            if (open == 0 && close == 0 && pair == 0) {
                
                // check if cur is present in the set
                if (!st.Contains(cur)) {
                    res.Add(cur);
                    st.Add(cur);
                }
            }
            return;
        }

        // if the current character is not a parenthesis
        if (str[index] != '(' && str[index] != ')') {
            
            // add the character to the current string
            findValid(str, index + 1, open, close, pair,
                      cur + str[index], res, st);
        }
        else {
            
            // if the current character is an open bracket
            if (str[index] == '(') {
                
                // reduce open count by 1,
                // and skip current character
                if (open > 0)
                    findValid(str, index + 1, open - 1,
                              close, pair, cur, res, st);

                // add the current character to the string
                findValid(str, index + 1, open, close,
                          pair + 1, cur + str[index], res,
                          st);
            }
            
            // else if the current character is a closed bracket
            else {
                
                // skip current character and
                // reduce closed count by 1
                if (close > 0)
                    findValid(str, index + 1, open,
                              close - 1, pair, cur, res,
                              st);
                
                // if there is an open pair, reduce
                // it and add the current character
                if (pair > 0)
                    findValid(str, index + 1, open, close,
                              pair - 1, cur + str[index],
                              res, st);
            }
        }
    }

    public List<string> validParenthesis(string str)
    {
        List<string> result = new List<string>();
        HashSet<string> st = new HashSet<string>();

        // to store count of invalid
        // open and closed paraenthesis
        int open = 0, close = 0;

        foreach(char c in str)
        {
            // if open bracket, increase
            // open invalid count by 1
            if (c == '(')
                open++;
            else if (c == ')') {
                
                // decrement invalid open
                // count by 1 if open is not 0
                if (open != 0)
                    open--;
                    
                // else increment invalid close
                // bracket count by 1
                else
                    close++;
            }
        }

        // recursive function to find all valid strings
        findValid(str, 0, open, close, 0, "", result, st);
        return result;
    }

    public static void Main()
    {
        string str = "()())()";
        GFG obj = new GFG();
        var res = obj.validParenthesis(str);

        foreach(var s in res) Console.WriteLine(s);
    }
}
JavaScript
// recursive function to find all valid strings
function findValid(str, index, open, close, pair, cur, res,
                   st)
{
    // base case, if end of string is reached
    if (index === str.length) {

        // check if all open and closed invalid
        // parenthesis are removed and no pair is left
        if (open === 0 && close === 0 && pair === 0) {
            
            // check if cur is present in the set
            if (!st.has(cur)) {
                res.push(cur);
                st.add(cur);
            }
        }
        return;
    }

    // if the current character is not a parenthesis
    if (str[index] !== "(" && str[index] !== ")") {
        
        // add the character to the current string
        findValid(str, index + 1, open, close, pair,
                  cur + str[index], res, st);
    }
    else {
        
        // if the current character is an open bracket
        if (str[index] === "(") {

            // reduce open count by 1,
            // and skip current character
            if (open > 0)
                findValid(str, index + 1, open - 1, close,
                          pair, cur, res, st);

            // add the current character to the string
            findValid(str, index + 1, open, close, pair + 1,
                      cur + str[index], res, st);
        }
        
        // else if the current character is a closed bracket
        else {

            // skip current character and
            // reduce closed count by 1
            if (close > 0)
                findValid(str, index + 1, open, close - 1,
                          pair, cur, res, st);
            
            // if there is an open pair, reduce
            // it and add the current character
            if (pair > 0)
                findValid(str, index + 1, open, close,
                          pair - 1, cur + str[index], res,
                          st);
        }
    }
}

function validParenthesis(str)
{
    let res = [];
    let st = new Set();

    // to store count of invalid
    // open and closed paraenthesis
    let open = 0, close = 0;

    for (let c of str) {
        
        // if open bracket, increase
        // open invalid count by 1
        if (c === "(")
            open++;
        else if (c === ")") {
            
            // decrement invalid open
            // count by 1 if open is not 0
            if (open !== 0)
                open--;
                
            // else increment invalid close
            // bracket count by 1
            else
                close++;
        }
    }

    // recursive function to find all valid strings
    findValid(str, 0, open, close, 0, "", res, st);
    return res;
}

// Driver code
let s = "()())()";
let result = validParenthesis(s);

for (let str of result)
    console.log(str);

Output
(())()
()()()
Comment