 Open in App
Not now

# Cost to Balance the parentheses

• Difficulty Level : Hard
• Last Updated : 26 Aug, 2022

Parentheses 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 parentheses in such a way that it is done in minimum cost. And shifting of parentheses by over one parentheses costs 1. If the parentheses can’t be balanced then print -1.

Examples :

Input : ()
Output :

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

 `// CPP code to calculate the minimum cost` `// to make the given parentheses balanced` `#include ` `using` `namespace` `std;`   `int` `costToBalance(string s)` `{` `    ``if` `(s.length() == 0)` `        ``cout << 0 << endl;`   `    ``// To store absolute count of` `    ``// balanced and unbalanced parentheses` `    ``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 == ``'('``)` `        ``a = 1;` `    ``else` `        ``a = -1;`   `    ``if` `(a < 0)` `        ``ans += ``abs``(a);`   `    ``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;` `}`

## Java

 `// 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 ` `        ``// parentheses` `        ``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)`

## Python3

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

## C#

 `// 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 ` `        ``// parentheses` `        ``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 == ``'('``)` `            ``a = 1;` `        ``else` `            ``a = -1;` `    `  `        ``if` `(a < 0)` `            ``ans += Math.Abs(a);` `    `  `        ``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)`

## Javascript

 ``

Output

```9
4```

Complexity Analysis:

• Time Complexity: O(N),N=String Length
• Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles