![]() |
VOOZH | about |
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:
Examples:
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
Approach :
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.
Algorithm :
- Create two variables open = 0 and close = 0
- Traverse on a string from i = 0 to i = n(size of string)
- If current element is '(' then increment open else if current element is ')' then increment close.
- While traversing check if count of close is greater than open or not if yes then print Impossible return to main
- After completion of traversal calculate (open-close) as that many times closing brackets required to make the sequence balanced.
Below is the implementation of the above approach:
(()(()()))
Complexity Analysis: