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.
Input : str = “()())()” - Output : ()()() (())() There are two possible solutions "()()()" and "(())()" Input : str = (v)())() Output : (v)()() (v())()
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.
(())() ()()() (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 contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Check for balanced parentheses in Python
- Check for balanced parentheses in an expression
- Print all combinations of balanced parentheses
- Pairs involved in Balanced Parentheses
- Check for balanced parentheses in an expression | O(1) space
- Length of longest balanced parentheses prefix
- Find the number of valid parentheses expressions of given length
- Minimum number of Parentheses to be added to make it valid
- Generate all the binary strings of N bits
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Maximum length of balanced string after swapping and removal of characters
- Java Program to print distinct permutations of a string
- Java ArrayList to print all possible words from phone digits
- Unique paths covering every non-obstacle block exactly once in a grid