Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.
Input: str = “)(()”
As by moving s to the end will make it valid.
Input: str = “()))(()”
Approach: Consider X as a valid bracket then definitely (X) is also valid. If X is not valid and can be balanced with just one change of position in some bracket then it must be of the type X = “)(“ where ‘)’ has been placed before ‘(‘.
Now, X can be replaced with (X) as it will not affect the balanced nature of X. The new string becomes X = “()()” which is balanced.
Hence, if (X) is balanced then we can say that X can be balanced with at most one change in the position of some bracket.
Below is the implementation of the above approach:
- Find the lexicographical next balanced bracket sequence
- Convert an unbalanced bracket sequence to a balanced sequence
- Find index of closing bracket for a given opening bracket in an expression
- Print the balanced bracket expression using given brackets
- Number of balanced bracket subsequence of length 2 and 4
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of bracket reversals needed to make an expression balanced
- Number of closing brackets needed to complete a regular bracket sequence
- Check if expression contains redundant bracket or not | Set 2
- Expression contains redundant bracket or not
- Print Bracket Number
- Minimum Swaps for Bracket Balancing
- Range Queries for Longest Correct Bracket Subsequence
- Construct Binary Tree from String with bracket representation
- Print all ways to break a string in bracket form
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.