Convert an unbalanced bracket sequence to a balanced sequence - GeeksforGeeks

13 May, 2021
Given an unbalanced bracket sequence of ‘(‘ and ‘)’, convert it into a balanced sequence by adding the minimum number of ‘(‘ at the beginning of the string and ‘)’ at the end of the string.
Examples: 
Input: str = “)))()” Output: “((()))()”
Input: str = “())())(())())” Output: “(((())())(())())”
Approach: 
Let us assume that whenever we encounter with opening bracket the depth increases by one and with a closing bracket the depth decreases by one.
Find the maximum negative depth in minDep and add that number of ‘(‘ at the beginning.
Then loop the new sequence to find the number of ‘)’s needed at the end of the string and add them.
Finally, return the string.
Below is the implementation of the approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return balancedBrackets stringstring balancedBrackets(string str){    // Initializing dep to 0    int dep = 0;     // Stores maximum negative depth    int minDep = 0;     for (int i = 0; i < str.length(); i++)    {        if (str[i] == '(')            dep++;        else            dep--;         // if dep is less than minDep        if (minDep > dep)            minDep = dep;    }     // if minDep is less than 0 then there    // is need to add '(' at the front    if (minDep < 0)    {        for (int i = 0; i < abs(minDep); i++)            str = '(' + str;    }     // Reinitializing to check the updated string    dep = 0;     for (int i = 0; i < str.length(); i++)    {        if (str[i] == '(')            dep++;        else            dep--;    }     // if dep is not 0 then there    // is need to add ')' at the back    if (dep != 0)    {        for (int i = 0; i < dep; i++)            str = str + ')';    }    return str;} // Driver codeint main(){    string str = ")))()";    cout << balancedBrackets(str);}
// Java implementation of the approachimport java.util.*; class GFG {     // Function to return balancedBrackets string    static String balancedBrackets(String str)    {        // Initializing dep to 0        int dep = 0;         // Stores maximum negative depth        int minDep = 0;         for (int i = 0; i < str.length(); i++)        {            if (str.charAt(i) == '(')                dep++;            else                dep--;             // if dep is less than minDep            if (minDep > dep)                minDep = dep;        }         // if minDep is less than 0 then there        // is need to add '(' at the front        if (minDep < 0)        {            for (int i = 0; i < Math.abs(minDep); i++)                str = '(' + str;        }         // Reinitializing to check the updated string        dep = 0;         for (int i = 0; i < str.length(); i++)        {            if (str.charAt(i) == '(')                dep++;            else                dep--;        }         // if dep is not 0 then there        // is need to add ')' at the back        if (dep != 0)        {            for (int i = 0; i < dep; i++)                str = str + ')';        }        return str;    }     // Driver code    public static void main(String[] args)    {        String str = ")))()";        System.out.println(balancedBrackets(str));    }} // This code is contributed by ihritik
# Python3 implementation of the approach # Function to return balancedBrackets String  def balancedBrackets(Str):     # Initializing dep to 0    dep = 0     # Stores maximum negative depth    minDep = 0     for i in Str:        if (i == '('):            dep += 1        else:            dep -= 1         # if dep is less than minDep        if (minDep > dep):            minDep = dep     # if minDep is less than 0 then there    # is need to add '(' at the front    if (minDep < 0):        for i in range(abs(minDep)):            Str = '(' + Str     # Reinitializing to check the updated String    dep = 0     for i in Str:        if (i == '('):            dep += 1        else:            dep -= 1     # if dep is not 0 then there    # is need to add ')' at the back    if (dep != 0):        for i in range(dep):            Str = Str + ')'     return Str  # Driver codeStr = ")))()"print(balancedBrackets(Str)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG {     // Function to return balancedBrackets string    static string balancedBrackets(string str)    {        // Initializing dep to 0        int dep = 0;         // Stores maximum negative depth        int minDep = 0;         for (int i = 0; i < str.Length; i++)        {            if (str[i] == '(')                dep++;            else                dep--;             // if dep is less than minDep            if (minDep > dep)                minDep = dep;        }         // if minDep is less than 0 then there        // is need to add '(' at the front        if (minDep < 0)        {            for (int i = 0; i < Math.Abs(minDep); i++)                str = '(' + str;        }         // Reinitializing to check the updated string        dep = 0;         for (int i = 0; i < str.Length; i++)        {            if (str[i] == '(')                dep++;            else                dep--;        }         // if dep is not 0 then there        // is need to add ')' at the back        if (dep != 0)        {            for (int i = 0; i < dep; i++)                str = str + ')';        }        return str;    }     // Driver code    public static void Main()    {        String str = ")))()";        Console.WriteLine(balancedBrackets(str));    }} // This code is contributed by ihritik
<script>      // JavaScript implementation of the approach      // Function to return balancedBrackets string      function balancedBrackets(str) {        // Initializing dep to 0        var dep = 0;         // Stores maximum negative depth        var minDep = 0;         for (var i = 0; i < str.length; i++) {          if (str[i] === "(") dep++;          else dep--;           // if dep is less than minDep          if (minDep > dep) minDep = dep;        }         // if minDep is less than 0 then there        // is need to add '(' at the front        if (minDep < 0) {          for (var i = 0; i < Math.abs(minDep); i++) str = "(" + str;        }         // Reinitializing to check the updated string        dep = 0;         for (var i = 0; i < str.length; i++) {          if (str[i] === "(") dep++;          else dep--;        }         // if dep is not 0 then there        // is need to add ')' at the back        if (dep !== 0) {          for (var i = 0; i < dep; i++) str = str + ")";        }        return str;      }       // Driver code      var str = ")))()";      document.write(balancedBrackets(str));    </script>
((()))()
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
ihritik
nidhi_biet
ujjwalgoel1103
rdtank
Constructive Algorithms
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Pairs with same Manhattan and Euclidean distance
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Multistage Graph (Shortest Path)
Runtime Errors
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string