Given an incomplete bracket sequence S. The task is to find the number of closing brackets ‘)’ needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print “IMPOSSIBLE”.
Let us define a regular bracket sequence in the following way:
- Empty string is a regular bracket sequence.
- If s is a regular bracket sequence, then (s) is a regular bracket sequence.
- If s & t are regular bracket sequences, then st is a regular bracket sequence.
Input : str = “(()(()(”
Output : (()(()()))
Explanation : The minimum number of ) needed to make the sequence regular are 3 which are appended at the end.
Input : str = “())(()”
Output : IMPOSSIBLE
We need to add minimal number of closing brackets ‘)’, so we will count the number of unbalanced opening brackets and then we will add that amount of closing brackets. If at any point the number of the closing bracket is greater than the opening bracket then the answer is IMPOSSIBLE.
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.
- Find index of closing bracket for a given opening bracket in an expression
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2
- Convert an unbalanced bracket sequence to a balanced sequence
- Minimum number of bracket reversals needed to make an expression balanced
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Count distinct regular bracket sequences which are not N periodic
- Find the lexicographical next balanced bracket sequence
- Minimum sum possible of any bracket sequence of length N
- Minimum Cost required to generate a balanced Bracket Sequence
- Find an equal point in a string of brackets
- Check if two expressions with brackets are same
- Balance a string after removing extra brackets
- Check for Balanced Brackets in an expression (well-formedness) using Stack
- Binary tree to string with brackets
- Number of balanced bracket expressions that can be formed from a string
- Number of balanced bracket subsequence of length 2 and 4
- Print Bracket Number
- Expression contains redundant bracket or not
- Range Queries for Longest Correct Bracket Subsequence
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.