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.
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.
- Count pairs of parentheses sequences such that parentheses are balanced
- Print all combinations of balanced parentheses
- Check for balanced parentheses in an expression
- Find the number of valid parentheses expressions of given length
- Length of longest balanced parentheses prefix
- Pairs involved in Balanced Parentheses
- Check for balanced parentheses in an expression | O(1) space
- Minimum number of Parentheses to be added to make it valid
- Check for balanced parentheses in Python
- Number of ways to insert two pairs of parentheses into a string of N characters
- Generate a combination of minimum coins that sums to a given value
- Check if K can be obtained by performing arithmetic operations on any permutation of an Array
- Generate all N digit numbers having absolute difference as K between adjacent digits
- Count of permutations of an Array having each element as a multiple or a factor of its index