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
- Pairs involved in Balanced Parentheses
- Check for balanced parentheses in an expression
- Print all combinations of 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
- Print all the permutations of a string without repetition using Collections in Java
- Maze With N doors and 1 Key
- Count number of ways to reach destination in a maze
- Print a given matrix in spiral form using direction tracking method
- Program to generate all possible valid IP addresses from given string | Set 2
- Rat in a Maze Problem when movement in all possible directions is allowed