Cost to Balance the parentheses

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 balanced



Input : ))((
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 :

  1. Store the braces in string.
  2. Run a loop to string size to store the count of opening and closing braces.
  3. Check if number of opening brace is equal to number of closing brace or not.
  4. If the braces are not equal then print -1 depicting that the string cant be balanced. Else proceed further.
  5. 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.
  6. 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).
  7. Finally we get the minimum cost in variable ans.

Below is the implementation of above approach :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int main()
{
    string s;
    s = ")))(((";
  
    cout << costToBalance(s) << endl;
  
    s = "))((";
    cout << costToBalance(s) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to calculate the 
// minimum cost to make the 
// given parentheses balanced
import 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)

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 code to calculate the minimum cost
# to make the given parentheses balanced
def 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 code
if __name__ == '__main__':
    s = ")))((("
  
    print(costToBalance(s))
    s = "))(("
    print(costToBalance(s))
      
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to calculate the 
// minimum cost to make the 
// given parentheses balanced
using 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)

chevron_right


Output:

9
4


My Personal Notes arrow_drop_up

Computer Science student during day Full stack developer at night

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.