VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-closing-brackets-needed-to-complete-a-regular-bracket-sequence/

⇱ Number of closing brackets needed to complete a regular bracket sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of closing brackets needed to complete a regular bracket sequence

Last Updated : 9 Sep, 2022

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.

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 :

  1. Create two variables open = 0 and close = 0
  2. Traverse on a string from i = 0 to i = n(size of string)
  3. If current element is '(' then increment open else if current element is ')' then increment close.
  4. While traversing check if count of close is greater than open or not if yes then print Impossible return to main 
  5. 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: 


Output
(()(()()))

Complexity Analysis:

  • Time Complexity: O(n) , where n is size of given string
  • Auxiliary Space: O(1) , as we are not using any extra space.
Comment
Article Tags: