Open In App

Convert an unbalanced bracket sequence to a balanced sequence

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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: “(((())())(())())”

Method 1:

Approach:

  • Initialize an empty stack.
  • Iterate over each character in the string.
  • If the character is an opening parenthesis, push it onto the stack.
  • If the character is a closing parenthesis, pop the most recent opening parenthesis from the stack if it matches the closing parenthesis, or push the closing parenthesis onto the stack if there is no matching opening parenthesis.
  • After iterating over all characters, count the remaining unbalanced parentheses on the stack and add the appropriate number of opening and closing parentheses to the beginning and end of the string to balance it.

C++




#include <bits/stdc++.h>
using namespace std;
 
// c++ code addition
 
string balance_parenthesis(string str){
    // Initialize an empty stack to keep track of opening and closing parentheses
    vector<int> st;
     
    // Iterate over each character in the input string
    for(auto c: str){
        // If the character is an opening parenthesis, push it onto the stack
        if(c == '(')
            st.push_back(c);
        // If the character is a closing parenthesis
        else if(c == ')')
            // If there is at least one opening parenthesis on the stack,
            // pop the most recent one
            if(st.size() > 0 && st[st.size() - 1] == '(')
                st.pop_back();
            // Otherwise, push the closing parenthesis onto the stack
            else
                st.push_back(c);
    }
     
    // Count the remaining unbalanced parentheses on the stack
    // and add the appropriate number of opening and closing parentheses
    // to the beginning and end of the output string to balance it.
    int closing = 0;
    int opening = 0;
    for(int i = 0; i < st.size(); i++){
        if(st[i] == '(') closing++;
        else if(st[i] == ')')opening++;
    }
     
    // Count the remaining unbalanced parentheses on the stack
    // and add the appropriate number of opening and closing parentheses
    // to the beginning and end of the output string to balance it.
    string res = "";
    for(int i = 0; i < opening ; i++)
        res = res + '(';
     
    res = res + str;
    for(int i = 0; i < closing; i++)
        res = res + ')';
     
    return res;
}
 
 
 
int main(){
     
     
    // Example usage
    string str = ")))()";
    cout << "Input:" << endl;
     
    cout << str << endl;
    string adjusted_s = balance_parenthesis(str);
    cout << "Balanced Parenthesis: " << endl;
    cout << adjusted_s << endl;
        
    return 0;
 
}
// Code Contributed by Arushi Jindal.


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
// java must be defined in a public class.
 
  
public class Main {
     
    // Javascript code addition
 
    public static String balance_parenthesis(String string){
        // Initialize an empty stack to keep track of opening and closing parentheses
        Stack<Character> stack = new Stack<Character>();
 
        // Iterate over each character in the input string
        for(int i = 0; i < string.length(); i++){
            // If the character is an opening parenthesis, push it onto the stack
            Character c = string.charAt(i);
 
            if(c == '(')
                stack.push(c);
            // If the character is a closing parenthesis
            else if(c == ')')
                // If there is at least one opening parenthesis on the stack,
                // pop the most recent one
                if(stack.size() > 0 && stack.peek() == '(')
                    stack.pop();
                // Otherwise, push the closing parenthesis onto the stack
                else
                    stack.push(c);
        }
 
        // Count the remaining unbalanced parentheses on the stack
        // and add the appropriate number of opening and closing parentheses
        // to the beginning and end of the output string to balance it.
        int closing = 0;
        int opening = 0;
        while(stack.size() > 0){
            if(stack.peek() == '(') closing++;
            else if(stack.peek() == ')')opening++;
            stack.pop();
        }
 
 
        // Count the remaining unbalanced parentheses on the stack
        // and add the appropriate number of opening and closing parentheses
        // to the beginning and end of the output string to balance it.
        String res = "";
        for(int i = 0; i < opening ; i++)
            res = res + '(';
 
        res = res + string;
        for(int i = 0; i < closing; i++)
            res = res + ')';
 
        return res;
    }
     
    public static void main(String[] args) {
 
        // Example usage
        String string = ")))()";
        System.out.println("Input:");
        System.out.println(string);
        String adjusted_s = balance_parenthesis(string);
        System.out.println("Balanced Parenthesis: ");
        System.out.println(adjusted_s);
    }
}
 
// The code is contributed by Nidhi goel.


Python3




def balance_parenthesis(string):
    # Initialize an empty stack to keep track of opening and closing parentheses
    stack = []
     
    # Iterate over each character in the input string
    for c in string:
        # If the character is an opening parenthesis, push it onto the stack
        if c == '(':
            stack.append(c)
        # If the character is a closing parenthesis
        elif c == ')':
            # If there is at least one opening parenthesis on the stack, pop the most recent one
            if len(stack) > 0 and stack[-1] == '(':
                stack.pop()
            # Otherwise, push the closing parenthesis onto the stack
            else:
                stack.append(c)
     
    # Count the remaining unbalanced parentheses on the stack
    # and add the appropriate number of opening and closing parentheses
    # to the beginning and end of the output string to balance it.
    return '(' * stack.count(')') + string + ')' * stack.count('(')
 
# Example usage
string = ")))()"
print("Input:")
print(string)
adjusted_s = balance_parenthesis(string)
print("Balanced Parenthesis: ")
print(adjusted_s)
 
#Code Contributed by SR.Dhanush


C#




// C# code addition
using System;
using System.Collections.Generic;
 
public class GFG {
    public static string balance_parenthesis(string str)
    {
        // Initialize an empty stack to keep track of
        // opening and closing parentheses
        List<char> st = new List<char>();
 
        // Iterate over each character in the input string
        foreach(char c in str)
        {
            // If the character is an opening parenthesis,
            // push it onto the stack
            if (c == '(')
                st.Add(c);
            // If the character is a closing parenthesis
            else if (c == ')')
                // If there is at least one opening
                // parenthesis on the stack, pop the most
                // recent one
                if (st.Count > 0 && st[st.Count - 1] == '(')
                    st.RemoveAt(st.Count - 1);
                // Otherwise, push the closing parenthesis
                // onto the stack
                else
                    st.Add(c);
        }
 
        // Count the remaining unbalanced parentheses on the
        // stack and add the appropriate number of opening
        // and closing parentheses to the beginning and end
        // of the output string to balance it.
        int closing = 0;
        int opening = 0;
        foreach(char c in st)
        {
            if (c == '(')
                closing++;
            else if (c == ')')
                opening++;
        }
 
        // Count the remaining unbalanced parentheses on the
        // stack and add the appropriate number of opening
        // and closing parentheses to the beginning and end
        // of the output string to balance it.
        string res = "";
        for (int i = 0; i < opening; i++)
            res += '(';
 
        res += str;
        for (int i = 0; i < closing; i++)
            res += ')';
 
        return res;
    }
 
    public static void Main()
    {
        // Example usage
        string str = ")))()";
        Console.WriteLine("Input:");
         
        Console.WriteLine(str);
        string adjusted_s = balance_parenthesis(str);
        Console.WriteLine("Balanced Parenthesis:");
        Console.WriteLine(adjusted_s);
    }
}
// This code is contributed by prasad264


Javascript




// Javascript code addition
 
function balance_parenthesis(string){
    // Initialize an empty stack to keep track of opening and closing parentheses
    let stack = [];
     
    // Iterate over each character in the input string
    for(let c of string){
        // If the character is an opening parenthesis, push it onto the stack
        if(c == '(')
            stack.push(c)
        // If the character is a closing parenthesis
        else if(c == ')')
            // If there is at least one opening parenthesis on the stack,
            // pop the most recent one
            if(stack.length > 0 && stack[-1] == '(')
                stack.pop()
            // Otherwise, push the closing parenthesis onto the stack
            else
                stack.push(c)
    }
     
    // Count the remaining unbalanced parentheses on the stack
    // and add the appropriate number of opening and closing parentheses
    // to the beginning and end of the output string to balance it.
    let closing = 0;
    let opening = 0;
    for(let i = 0; i < stack.length; i++){
        if(stack[i] == '(') closing++;
        else if(stack[i] == ')')opening++;
    }
     
    return '('.repeat(opening-1) + string + ')'.repeat(closing-1)
}
 
// Example usage
let string = ")))()"
console.log("Input:")
console.log(string)
adjusted_s = balance_parenthesis(string)
console.log("Balanced Parenthesis: ")
console.log(adjusted_s)
 
// Code Contributed by Arushi Jindal.


Output

Input:
)))()
Balanced Parenthesis: 
((()))()

Time Complexity:  O(n), where n is size of String.

Auxiliary Space:  O(1).

Method 2:

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return balancedBrackets string
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 < 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
int main()
{
    string str = ")))()";
    cout << balancedBrackets(str);
}


Java




// Java implementation of the approach
import 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




# 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 code
Str = ")))()"
print(balancedBrackets(Str))
 
# This code is contributed by Mohit Kumar


C#




// C# implementation of the approach
using 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


Javascript




<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>


Output

((()))()

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 25 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads