Cost to Balance the parentheses - GeeksforGeeks

25 May, 2021
Parenthesis are said to be balanced when every opening brace has a closing brace like “()()” or “(())” or “(()())” etc. Incorrect balancing includes “)(” or “))((”  etc. The task here is to correct the sequence of parenthesis in such a way that it is done in minimum cost. And shifting of parenthesis by over one parentheses costs 1. If the parenthesis can’t be balanced then print -1.Examples :
Input : () Output : 0 Explanation : Already balancedInput : ))(( Output : 4 Explanation : Firstly, ) at position 1st goes to the last position, costing 3, so we get )((). Then, ) at position 1st goes to the 2nd position costing 1. So, finally we get ()(). Therefore, the total cost is 4.
Algorithm :  
Store the braces in string.Run a loop to string size to store the count of opening and closing braces.Check if number of opening brace is equal to number of closing brace or not.If the braces are not equal then print -1 depicting that the string cant be balanced. Else proceed further.Initially, Check at 0th index that whether the string contains opening brace or closing brace. If we get an opening brace then store +1 in the array at index 0, else if closing brace is present then place -1 at 0th index.Now run a loop from 1st index to array length.If opening brace is present at index i then add +1 to value at previous index i.e. i-1 and store sum at index i.If closing brace is present at index i then add -1 to value at previous index i.e. i-1 and store sum at index i.If value at index i is negative i.e less than 0, then add the absolute value of array[i] into a variable(ans in below program).Finally we get the minimum cost in variable ans.
Store the braces in string.
Run a loop to string size to store the count of opening and closing braces.
Check if number of opening brace is equal to number of closing brace or not.
If the braces are not equal then print -1 depicting that the string cant be balanced. Else proceed further.
Initially, Check at 0th index that whether the string contains opening brace or closing brace. If we get an opening brace then store +1 in the array at index 0, else if closing brace is present then place -1 at 0th index.
Now run a loop from 1st index to array length.If opening brace is present at index i then add +1 to value at previous index i.e. i-1 and store sum at index i.If closing brace is present at index i then add -1 to value at previous index i.e. i-1 and store sum at index i.If value at index i is negative i.e less than 0, then add the absolute value of array[i] into a variable(ans in below program).
If opening brace is present at index i then add +1 to value at previous index i.e. i-1 and store sum at index i.
If closing brace is present at index i then add -1 to value at previous index i.e. i-1 and store sum at index i.
If value at index i is negative i.e less than 0, then add the absolute value of array[i] into a variable(ans in below program).
Finally we get the minimum cost in variable ans.
Below is the implementation of above approach :  
C++
Java
Python3
C#
Javascript
// CPP code to calculate the minimum cost// to make the given parentheses balanced#include <bits/stdc++.h>using namespace std; int costToBalance(string s){    if (s.length() == 0)        cout << 0 << endl;     // To store absolute count of    // balanced and unbalanced parenthesis    int ans = 0;     // o(open bracket) stores count of '(' and    // c(close bracket) stores count of ')'    int o = 0, c = 0;     for (int i = 0; i < s.length(); i++) {        if (s[i] == '(')            o++;        if (s[i] == ')')            c++;    }     if (o != c)        return -1;     int a[s.size()];    if (s[0] == '(')        a[0] = 1;    else        a[0] = -1;     if (a[0] < 0)        ans += abs(a[0]);     for (int i = 1; i < s.length(); i++) {        if (s[i] == '(')            a[i] = a[i - 1] + 1;        else            a[i] = a[i - 1] - 1;        if (a[i] < 0)            ans += abs(a[i]);    }     return ans;} // Driver codeint main(){    string s;    s = ")))(((";     cout << costToBalance(s) << endl;     s = "))((";    cout << costToBalance(s) << endl;     return 0;}
// Java code to calculate the// minimum cost to make the// given parentheses balancedimport java.io.*; class GFG{    static int costToBalance(String s)    {        if (s.length() == 0)            System.out.println(0);             // To store absolute count        // of balanced and unbalanced        // parenthesis        int ans = 0;             // o(open bracket) stores count        // of '(' and c(close bracket)        // stores count of ')'        int o = 0, c = 0;             for (int i = 0; i < s.length(); i++)        {            if (s.charAt(i) == '(')                o++;            if (s.charAt(i) == ')')                c++;        }             if (o != c)            return -1;             int []a = new int[s.length()];        if (s.charAt(0) == '(')            a[0] = 1;        else            a[0] = -1;             if (a[0] < 0)            ans += Math.abs(a[0]);             for (int i = 1; i < s.length(); i++)        {            if (s.charAt(i) == '(')                a[i] = a[i - 1] + 1;            else                a[i] = a[i - 1] - 1;            if (a[i] < 0)                ans += Math.abs(a[i]);        }             return ans;    }         // Driver code    public static void main(String args[])    {        String s;        s = ")))(((";             System.out.println(costToBalance(s));             s = "))((";        System.out.println(costToBalance(s));    }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python 3 code to calculate the minimum cost# to make the given parentheses balanceddef costToBalance(s):    if (len(s) == 0):        print(0)     # To store absolute count of    # balanced and unbalanced parenthesis    ans = 0     # o(open bracket) stores count of '(' and    # c(close bracket) stores count of ')'    o = 0    c = 0     for i in range(len(s)):        if (s[i] == '('):            o += 1        if (s[i] == ')'):            c += 1     if (o != c):        return -1     a = [0 for i in range(len(s))]    if (s[0] == '('):        a[0] = 1    else:        a[0] = -1     if (a[0] < 0):        ans += abs(a[0])     for i in range(1, len(s)):        if (s[i] == '('):            a[i] = a[i - 1] + 1        else:            a[i] = a[i - 1] - 1        if (a[i] < 0):            ans += abs(a[i])     return ans # Driver codeif __name__ == '__main__':    s = ")))((("     print(costToBalance(s))    s = "))(("    print(costToBalance(s))     # This code is contributed by# Surendra_Gangwar
// C# code to calculate the// minimum cost to make the// given parentheses balancedusing System; class GFG{    static int costToBalance(string s)    {        if (s.Length == 0)            Console.WriteLine(0);             // To store absolute count        // of balanced and unbalanced        // parenthesis        int ans = 0;             // o(open bracket) stores count        // of '(' and c(close bracket)        // stores count of ')'        int o = 0, c = 0;             for (int i = 0; i < s.Length; i++)        {            if (s[i] == '(')                o++;            if (s[i] == ')')                c++;        }             if (o != c)            return -1;             int []a = new int[s.Length];        if (s[0] == '(')            a[0] = 1;        else            a[0] = -1;             if (a[0] < 0)            ans += Math.Abs(a[0]);             for (int i = 1; i < s.Length; i++)        {            if (s[i] == '(')                a[i] = a[i - 1] + 1;            else                a[i] = a[i - 1] - 1;            if (a[i] < 0)                ans += Math.Abs(a[i]);        }             return ans;    }         // Driver code    static void Main()    {        string s;        s = ")))(((";             Console.WriteLine (costToBalance(s));             s = "))((";        Console.WriteLine (costToBalance(s));    }} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // javascript code to calculate the// minimum cost to make the// given parentheses balanced     function costToBalance( s)    {        if (s.length == 0)            document.write(0);             // To store absolute count        // of balanced and unbalanced        // parenthesis        var ans = 0;             // o(open bracket) stores count        // of '(' and c(close bracket)        // stores count of ')'        var o = 0, c = 0;             for (var i = 0; i < s.length; i++)        {            if (s[i] == '(')                o++;            if (s[i] == ')')                c++;        }             if (o != c)            return -1;             var a = new Array(s.Length);        if (s[0] == '(')            a[0] = 1;        else            a[0] = -1;             if (a[0] < 0)            ans += Math.abs(a[0]);             for (var i = 1; i < s.length; i++)        {            if (s[i] == '(')                a[i] = a[i - 1] + 1;            else                a[i] = a[i - 1] - 1;            if (a[i] < 0)                ans += Math.abs(a[i]);        }             return ans;    }         // Driver code        var s;        s = ")))(((";             document.write(costToBalance(s) + "<br>");             s = "))((";        document.write(costToBalance(s) + "<br>" ); // This code is contributed by bunnyram19.</script>
9
4
 
Time Complexity:O(N),N=String Length
Auxiliary Space:O(N)
manishshaw1
SURENDRA_GANGWAR
Akanksha_Rai
aditya7409
bunnyram19
cpp-string
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
3 Different ways to print Fibonacci series in Java
Find whether an array is subset of another array | Added Method 5
Given a sorted and rotated array, find if there is a pair with a given sum
Program to remove vowels from a String
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string