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
- Minimum Cost required to generate a balanced Bracket Sequence
- Number of balanced bracket expressions that can be formed from a string
- Find index of closing bracket for a given opening bracket in an expression
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum number of bracket reversals needed to make an expression balanced
- Print the balanced bracket expression using given brackets
- Number of balanced bracket subsequence of length 2 and 4
- Number of closing brackets needed to complete a regular bracket sequence
- Minimum sum possible of any bracket sequence of length N
- InfyTQ 2019 : Find the position from where the parenthesis is not balanced
- Minimum operation required to make a balanced sequence
- Find element position in given monotonic sequence
- Find the Kth position element of the given sequence
- Check if permutation of a given string can be made palindromic by removing at most K characters
- Total position where king can reach on a chessboard in exactly M moves | Set 2
- Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
- Range Queries for Longest Correct Bracket Subsequence Set | 2
- Maximum inversions in a sequence of 1 to N after performing given operations at most K times
- Insert N elements in a Linked List one after other at middle position
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.