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:
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.
- Convert an unbalanced bracket sequence to a balanced sequence
- Find the lexicographical next balanced bracket sequence
- Minimum Cost required to generate a balanced Bracket Sequence
- Find index of closing bracket for a given opening bracket in an expression
- Minimum number of bracket reversals needed to make an expression balanced
- Number of balanced bracket subsequence of length 2 and 4
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Print the balanced bracket expression using given brackets
- Number of closing brackets needed to complete a regular bracket sequence
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Check if X can give change to every person in the Queue
- Check if a string can be formed from another string by at most X circular clockwise shifts
- Check if expression contains redundant bracket or not | Set 2
- Find the Kth position element of the given sequence
- Second most repeated word in a sequence
- Second most repeated word in a sequence in Python
- Count of pairs of strings which differ in exactly one position
- Check if frequency of all characters can become same by one removal
- Meta Strings (Check if two strings can become same after a swap in one string)
- Check if characters of one string can be swapped to form other
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.