Given a 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: The problem can be solved using a stack as discussed in this post. In this article, an approach which doesn’t use extra space will be discussed.
If the frequency of ‘(‘ is less than frequency of ‘)’. If the above difference is greater than 1 then the sequence cannot be balanced else it can be balanced if the overall difference is zero.
Below is implementation of the above approach:
- 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
- Number of balanced bracket expressions that can be formed from a string
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of bracket reversals needed to make an expression balanced
- Minimum sum possible of any bracket sequence of length N
- Number of closing brackets needed to complete a regular bracket sequence
- Expression contains redundant bracket or not
- Print Bracket Number
- Range Queries for Longest Correct Bracket Subsequence Set | 2
- Construct Binary Tree from String with bracket representation
- Range Queries for Longest Correct Bracket Subsequence
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
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.