Minimum number of bracket reversals needed to make an expression balanced

Last Updated : 09 Nov, 2023

Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.
Examples:

`Input:  exp = "}{"Output: 2We need to change '}' to '{' and '{' to'}' so that the expression becomes balanced, the balanced expression is '{}'Input:  exp = "{{{"Output: Can't be made balanced using reversalsInput:  exp = "{{{{"Output: 2 Input:  exp = "{{{{}}"Output: 1 Input:  exp = "}{{}}{{{"Output: 3`
Recommended Practice

One simple observation is, the string can be balanced only if total number of brackets is even (there must be equal no of ‘{‘ and ‘}’)
A Naive Solution is to consider every bracket and recursively count number of reversals by taking two cases (i) keeping the bracket as it is (ii) reversing the bracket. If we get a balanced expression, we update result if number of steps followed for reaching here is smaller than the minimum so far.

Steps to implement

• Check for the length of the given expression, if it is odd then return -1
• If it is even then call a recursive function
• That recursive function once leaves a bracket as it is and once reverses a bracket
• After each recursive call, we will check whether the modified string is balanced or not
• If the modified string is balanced and the number of reversals to reach this string is minimum from all the answers found till now then keep this answer stored somewhere
• In the function for checking whether the string is balanced or not, we will initially keep count=0.
• After that traverse the string and if we got ‘{then increment the count else decrement the count
• If at any point count becomes negative then this means there are more Closing brackets than opening ones. Hence string is not balanced
• At last, if the count is not equal to 0 then that means there are more opening brackets than closing ones. Hence string is not balanced
• If we never found that there are more Closing brackets than opening ones or there are more opening brackets than closing ones then the string is balanced

Code-

C++

 `// C++ program to find minimum number of` `// reversals required to balance an expression` `#include ` `using` `namespace` `std;`   `//Function to check that expression is balanced or not` `bool` `isBalanced(string expr)` `{` `    ``// Initialising Variables` `    ``bool` `flag = ``true``;` `    ``int` `count = 0;` ` `  `    ``// Traversing the Expression` `    ``for` `(``int` `i = 0; i < expr.length(); i++) {` ` `  `        ``if` `(expr[i] == ``'{'``) {` `            ``count++;` `        ``}` `        ``else` `{` `            ``// It is a closing bracket` `            ``count--;` `        ``}` `        ``if` `(count < 0) {` `            ``// This means there are more Closing brackets` `            ``// than opening ones` `            ``flag = ``false``;` `            ``break``;` `        ``}` `    ``}` ` `  `    ``// If count is not zero,` `    ``// It means there are` `    ``// more opening brackets` `    ``if` `(count != 0) {` `        ``flag = ``false``;` `    ``}` ` `  `    ``return` `flag;` `}`     `//Recursive Function for finding ` `//Number of reversals` `void` `recur(string expr,``int` `n,``int` `ind,``int` `change,``int` `&ans){` `    ``//When generated expression is balanced` `    ``if``(isBalanced(expr)){ans=min(ans,change);}` `    `  `    ``//When we covered whole string` `    ``if``(ind==n){``return``;}` `    `  `    ``//Keep bracket as it is` `    ``recur(expr,n,ind+1,change,ans);` `    `  `    ``//Reverse the bracket` `    ``if``(expr[ind]==``'{'``){expr[ind]=``'}'``;}` `    ``else``{expr[ind]=``'{'``;}` `    ``recur(expr,n,ind+1,change+1,ans);` `}`         `// Returns count of minimum reversals for making` `// expr balanced. Returns -1 if expr cannot be` `// balanced.` `int` `countMinReversals(string expr)` `{` `    ``//Length of expression` `    ``int` `n = expr.length();` `    `  `    ``//To store answer` `    ``int` `ans=INT_MAX;` `    `  `    ``//When total number of brackets are odd` `    ``if``(n%2==1){` `        ``return` `-1;` `    ``}``else``{` `        ``//Function call for finding answer` `        ``recur(expr,n,0,0,ans);` `        ``return` `ans;` `    ``}` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``string expr = ``"}}{{"``;` `    ``cout << countMinReversals(expr);` `    ``return` `0;` `}`

Java

 `public` `class` `MinReversalsToBalance {`   `    ``// Function to check if the expression is balanced or` `    ``// not` `    ``public` `static` `boolean` `isBalanced(String expr)` `    ``{` `        ``// Initializing variables` `        ``boolean` `flag = ``true``;` `        ``int` `count = ``0``;`   `        ``// Traversing the expression` `        ``for` `(``char` `c : expr.toCharArray()) {` `            ``if` `(c == ``'{'``) {` `                ``count++;` `            ``}` `            ``else` `{` `                ``// It is a closing bracket` `                ``count--;` `            ``}` `            ``if` `(count < ``0``) {` `                ``// This means there are more closing` `                ``// brackets than opening ones` `                ``flag = ``false``;` `                ``break``;` `            ``}` `        ``}`   `        ``// If count is not zero, it means there are more` `        ``// opening brackets` `        ``if` `(count != ``0``) {` `            ``flag = ``false``;` `        ``}`   `        ``return` `flag;` `    ``}`   `    ``// Recursive function for finding the number of` `    ``// reversals` `    ``public` `static` `void` `recur(String expr, ``int` `n, ``int` `ind,` `                             ``int` `change, ``int``[] ans)` `    ``{` `        ``// When we've covered the whole string, check if` `        ``// it's balanced` `        ``if` `(ind == n) {` `            ``if` `(isBalanced(expr)) {` `                ``ans[``0``] = Math.min(ans[``0``], change);` `            ``}` `            ``return``;` `        ``}`   `        ``// Keep the bracket as it is` `        ``recur(expr, n, ind + ``1``, change, ans);`   `        ``// Reverse the bracket` `        ``if` `(expr.charAt(ind) == ``'{'``) {` `            ``expr = expr.substring(``0``, ind) + ``'}'` `                   ``+ expr.substring(ind + ``1``);` `        ``}` `        ``else` `{` `            ``expr = expr.substring(``0``, ind) + ``'{'` `                   ``+ expr.substring(ind + ``1``);` `        ``}` `        ``recur(expr, n, ind + ``1``, change + ``1``, ans);` `    ``}`   `    ``// Returns the count of minimum reversals for making` `    ``// expr balanced. Returns -1 if expr cannot be balanced.` `    ``public` `static` `int` `countMinReversals(String expr)` `    ``{` `        ``// Length of the expression` `        ``int` `n = expr.length();`   `        ``// To store the answer` `        ``int``[] ans = { Integer.MAX_VALUE };`   `        ``// When the total number of brackets is odd` `        ``if` `(n % ``2` `== ``1``) {` `            ``return` `-``1``;` `        ``}` `        ``else` `{` `            ``// Function call for finding the answer` `            ``recur(expr, n, ``0``, ``0``, ans);` `            ``if` `(ans[``0``] == Integer.MAX_VALUE) {` `                ``return` `-``1``;` `            ``}` `            ``return` `ans[``0``];` `        ``}` `    ``}`   `    ``// Driver program to test the function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String expr = ``"}}{{"``;` `        ``int` `result = countMinReversals(expr);` `        ``System.out.println(result);` `    ``}` `}`

Python

 `# Function to check if the expression is balanced or not` `def` `isBalanced(expr):` `    ``# Initializing variables` `    ``flag ``=` `True` `    ``count ``=` `0`   `    ``# Traversing the expression` `    ``for` `char ``in` `expr:` `        ``if` `char ``=``=` `'{'``:` `            ``count ``+``=` `1` `        ``else``:` `            ``# It is a closing bracket` `            ``count ``-``=` `1` `        ``if` `count < ``0``:` `            ``# This means there are more closing brackets than opening ones` `            ``flag ``=` `False` `            ``break`   `    ``# If count is not zero, it means there are more opening brackets` `    ``if` `count !``=` `0``:` `        ``flag ``=` `False`   `    ``return` `flag`   `# Recursive function for finding the number of reversals`     `def` `recur(expr, n, ind, change, ans):` `    ``# When we've covered the whole string, check if it's balanced` `    ``if` `ind ``=``=` `n:` `        ``if` `isBalanced(expr):` `            ``ans[``0``] ``=` `min``(ans[``0``], change)` `        ``return`   `    ``# Keep the bracket as it is` `    ``recur(expr, n, ind ``+` `1``, change, ans)`   `    ``# Reverse the bracket` `    ``if` `expr[ind] ``=``=` `'{'``:` `        ``expr ``=` `expr[:ind] ``+` `'}'` `+` `expr[ind ``+` `1``:]` `    ``else``:` `        ``expr ``=` `expr[:ind] ``+` `'{'` `+` `expr[ind ``+` `1``:]` `    ``recur(expr, n, ind ``+` `1``, change ``+` `1``, ans)`   `# Returns the count of minimum reversals for making expr balanced.` `# Returns -1 if expr cannot be balanced.`     `def` `countMinReversals(expr):` `    ``# Length of the expression` `    ``n ``=` `len``(expr)`   `    ``# To store the answer` `    ``ans ``=` `[``float``(``'inf'``)]`   `    ``# When the total number of brackets is odd` `    ``if` `n ``%` `2` `=``=` `1``:` `        ``return` `-``1` `    ``else``:` `        ``# Function call for finding the answer` `        ``recur(expr, n, ``0``, ``0``, ans)` `        ``if` `ans[``0``] ``=``=` `float``(``'inf'``):` `            ``return` `-``1` `        ``return` `ans[``0``]`     `# Driver program to test the function` `if` `__name__ ``=``=` `"__main__"``:` `    ``expr ``=` `"}}{{"` `    ``result ``=` `countMinReversals(expr)` `    ``print``(result)`

C#

 `using` `System;`   `class` `Program` `{` `    ``// Function to check if the expression is balanced or not` `    ``static` `bool` `IsBalanced(``string` `expr)` `    ``{` `        ``bool` `flag = ``true``;` `        ``int` `count = 0;`   `        ``// Traversing the expression` `        ``for` `(``int` `i = 0; i < expr.Length; i++)` `        ``{` `            ``if` `(expr[i] == ``'{'``)` `            ``{` `                ``count++;` `            ``}` `            ``else` `            ``{` `                ``// It is a closing bracket` `                ``count--;` `            ``}`   `            ``if` `(count < 0)` `            ``{` `                ``// This means there are more closing brackets than opening ones` `                ``flag = ``false``;` `                ``break``;` `            ``}` `        ``}`   `        ``// If count is not zero, it means there are more opening brackets` `        ``if` `(count != 0)` `        ``{` `            ``flag = ``false``;` `        ``}`   `        ``return` `flag;` `    ``}`   `    ``// Recursive function for finding the number of reversals` `    ``static` `void` `Recur(``string` `expr, ``int` `n, ``int` `ind, ``int` `change, ``ref` `int` `ans)` `    ``{` `        ``// When the generated expression is balanced` `        ``if` `(IsBalanced(expr))` `        ``{` `            ``ans = Math.Min(ans, change);` `        ``}`   `        ``// When we've covered the whole string` `        ``if` `(ind == n)` `        ``{` `            ``return``;` `        ``}`   `        ``// Keep the bracket as it is` `        ``Recur(expr, n, ind + 1, change, ``ref` `ans);`   `        ``// Reverse the bracket` `        ``if` `(expr[ind] == ``'{'``)` `        ``{` `            ``expr = expr.Remove(ind, 1).Insert(ind, ``"}"``);` `        ``}` `        ``else` `        ``{` `            ``expr = expr.Remove(ind, 1).Insert(ind, ``"{"``);` `        ``}`   `        ``Recur(expr, n, ind + 1, change + 1, ``ref` `ans);` `    ``}`   `    ``// Returns the count of minimum reversals for making the expression balanced.` `    ``// Returns -1 if the expression cannot be balanced.` `    ``static` `int` `CountMinReversals(``string` `expr)` `    ``{` `        ``int` `n = expr.Length;` `        ``int` `ans = ``int``.MaxValue;`   `        ``// When the total number of brackets is odd` `        ``if` `(n % 2 == 1)` `        ``{` `            ``return` `-1;` `        ``}` `        ``else` `        ``{` `            ``// Function call for finding the answer` `            ``Recur(expr, n, 0, 0, ``ref` `ans);` `            ``return` `ans;` `        ``}` `    ``}`   `    ``// Driver program to test the above function` `    ``static` `void` `Main()` `    ``{` `        ``string` `expr = ``"}}{{"``;` `        ``Console.WriteLine(CountMinReversals(expr));` `    ``}` `}`

Javascript

 `// Function to check if the expression is balanced or not` `function` `isBalanced(expr) {` `    ``// Initializing variables` `    ``let flag = ``true``;` `    ``let count = 0;`   `    ``// Traversing the expression` `    ``for` `(let i = 0; i < expr.length; i++) {` `        ``let c = expr[i];` `        ``if` `(c === ``'{'``) {` `            ``count++;` `        ``} ``else` `{` `            ``// It is a closing bracket` `            ``count--;` `        ``}` `        ``if` `(count < 0) {` `            ``// This means there are more closing brackets than opening ones` `            ``flag = ``false``;` `            ``break``;` `        ``}` `    ``}`   `    ``// If count is not zero, it means there are more opening brackets` `    ``if` `(count !== 0) {` `        ``flag = ``false``;` `    ``}`   `    ``return` `flag;` `}`   `// Recursive function for finding the number of reversals` `function` `recur(expr, ind, change, ans) {` `    ``const n = expr.length;`   `    ``// When we've covered the whole string, check if it's balanced` `    ``if` `(ind === n) {` `        ``if` `(isBalanced(expr)) {` `            ``ans[0] = Math.min(ans[0], change);` `        ``}` `        ``return``;` `    ``}`   `    ``// Keep the bracket as it is` `    ``recur(expr, ind + 1, change, ans);`   `    ``// Reverse the bracket` `    ``if` `(expr[ind] === ``'{'``) {` `        ``expr = expr.substring(0, ind) + ``'}'` `+ expr.substring(ind + 1);` `    ``} ``else` `{` `        ``expr = expr.substring(0, ind) + ``'{'` `+ expr.substring(ind + 1);` `    ``}` `    ``recur(expr, ind + 1, change + 1, ans);` `}`   `// Returns the count of minimum reversals for making expr balanced. Returns -1 if expr cannot be balanced.` `function` `countMinReversals(expr) {` `    ``// To store the answer` `    ``const ans = [Number.MAX_SAFE_INTEGER];`   `    ``// Length of the expression` `    ``const n = expr.length;`   `    ``// When the total number of brackets is odd` `    ``if` `(n % 2 === 1) {` `        ``return` `-1;` `    ``} ``else` `{` `        ``// Function call for finding the answer` `        ``recur(expr, 0, 0, ans);` `        ``if` `(ans[0] === Number.MAX_SAFE_INTEGER) {` `            ``return` `-1;` `        ``}` `        ``return` `ans[0];` `    ``}` `}`   `// Driver program to test the function` `const expr = ``"}}{{"``;` `const result = countMinReversals(expr);` `console.log(result);`

Output-

`2`

Time complexity: O(2n*n), because O(2n) in recursive function and O(n) in checking the expression generated after every recursive call is balanced or not

Space Complexity: O(n), because of the Auxillary space of recursion

An Efficient Solution can solve this problem in O(n) time. The idea is to first remove all balanced part of expression. For example, convert “}{{}}{{{” to “}{{{” by removing highlighted part. If we take a closer look, we can notice that, after removing balanced part, we always end up with an expression of the form }}…}{{…{, an expression that contains 0 or more number of closing brackets followed by 0 or more numbers of opening brackets.
How many minimum reversals are required for an expression of the form “}}..}{{..{” ?. Let m be the total number of closing brackets and n be the number of opening brackets. We need &#x2308m/2&#x2309 + &#x2308n/2&#x2309 reversals. For example }}}}{{ requires 2+1 reversals.
Below is implementation of above idea:

C++14

 `// C++ program to find minimum number of` `// reversals required to balance an expression` `#include ` `using` `namespace` `std;`   `// Returns count of minimum reversals for making` `// expr balanced. Returns -1 if expr cannot be` `// balanced.` `int` `countMinReversals(string expr)` `{` `    ``int` `len = expr.length();`   `    ``// length of expression must be even to make` `    ``// it balanced by using reversals.` `    ``if` `(len % 2)` `        ``return` `-1;`   `    ``// After this loop, stack contains unbalanced` `    ``// part of expression, i.e., expression of the` `    ``// form "}}..}{{..{"` `    ``stack<``char``> s;` `    ``for` `(``int` `i = 0; i < len; i++) {` `        ``if` `(expr[i] == ``'}'` `&& !s.empty()) {` `            ``if` `(s.top() == ``'{'``)` `                ``s.pop();` `            ``else` `                ``s.push(expr[i]);` `        ``}` `        ``else` `            ``s.push(expr[i]);` `    ``}`   `    ``// Length of the reduced expression` `    ``// red_len = (m+n)` `    ``int` `red_len = s.size();`   `    ``// count opening brackets at the end of` `    ``// stack` `    ``int` `n = 0;` `    ``while` `(!s.empty() && s.top() == ``'{'``) {` `        ``s.pop();` `        ``n++;` `    ``}`   `    ``// return ceil(m/2) + ceil(n/2) which is` `    ``// actually equal to (m+n)/2 + n%2 when` `    ``// m+n is even.` `    ``return` `(red_len / 2 + n % 2);` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``string expr = ``"}}{{"``;` `    ``cout << countMinReversals(expr);` `    ``return` `0;` `}`

Java

 `// Java Code to count minimum reversal for` `// making an expression balanced.`   `import` `java.util.Stack;`   `public` `class` `GFG {`   `    ``// Method count minimum reversal for` `    ``// making an expression balanced.` `    ``// Returns -1 if expression cannot be balanced` `    ``static` `int` `countMinReversals(String expr)` `    ``{` `        ``int` `len = expr.length();`   `        ``// length of expression must be even to make` `        ``// it balanced by using reversals.` `        ``if` `(len % ``2` `!= ``0``)` `            ``return` `-``1``;`   `        ``// After this loop, stack contains unbalanced` `        ``// part of expression, i.e., expression of the` `        ``// form "}}..}{{..{"` `        ``Stack s = ``new` `Stack<>();`   `        ``for` `(``int` `i = ``0``; i < len; i++) {` `            ``char` `c = expr.charAt(i);` `            ``if` `(c == ``'}'` `&& !s.empty()) {` `                ``if` `(s.peek() == ``'{'``)` `                    ``s.pop();` `                ``else` `                    ``s.push(c);` `            ``}` `            ``else` `                ``s.push(c);` `        ``}`   `        ``// Length of the reduced expression` `        ``// red_len = (m+n)` `        ``int` `red_len = s.size();`   `        ``// count opening brackets at the end of` `        ``// stack` `        ``int` `n = ``0``;` `        ``while` `(!s.empty() && s.peek() == ``'{'``) {` `            ``s.pop();` `            ``n++;` `        ``}`   `        ``// return ceil(m/2) + ceil(n/2) which is` `        ``// actually equal to (m+n)/2 + n%2 when` `        ``// m+n is even.` `        ``return` `(red_len / ``2` `+ n % ``2``);` `    ``}`   `    ``// Driver method` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String expr = ``"}}{{"``;`   `        ``System.out.println(countMinReversals(expr));` `    ``}` `}` `// This code is contributed by Sumit Ghosh`

Python3

 `# Python3 program to find minimum number of` `# reversals required to balance an expression`   `# Returns count of minimum reversals` `# for making expr balanced. Returns -1` `# if expr cannot be balanced.`     `def` `countMinReversals(expr):`   `    ``lenn ``=` `len``(expr)`   `    ``# length of expression must be even` `    ``# to make it balanced by using reversals.` `    ``if` `(lenn ``%` `2``):` `        ``return` `-``1`   `    ``# After this loop, stack contains` `    ``# unbalanced part of expression,` `    ``# i.e., expression of the form "...."` `    ``s ``=` `[]` `    ``for` `i ``in` `range``(lenn):` `        ``if` `(expr[i] ``=``=` `'}'` `and` `len``(s)):`   `            ``if` `(s[``0``] ``=``=` `'{'``):` `                ``s.pop(``0``)` `            ``else``:` `                ``s.insert(``0``, expr[i])` `        ``else``:` `            ``s.insert(``0``, expr[i])`   `    ``# Length of the reduced expression` `    ``# red_len = (m+n)` `    ``red_len ``=` `len``(s)`   `    ``# count opening brackets at the` `    ``# end of stack` `    ``n ``=` `0` `    ``while` `(``len``(s)``and` `s[``0``] ``=``=` `'{'``):` `        ``s.pop(``0``)` `        ``n ``+``=` `1`   `    ``# return ceil(m/2) + ceil(n/2) which` `    ``# is actually equal to (m+n)/2 + n%2` `    ``# when m+n is even.` `    ``return` `(red_len ``/``/` `2` `+` `n ``%` `2``)`     `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``expr ``=` `"}{"` `    ``print``(countMinReversals(expr.strip()))`   `# This code is contributed by` `# Shubham Singh(SHUBHAMSINGH10)`

C#

 `// C# Code to count minimum reversal for` `// making an expression balanced.` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `    ``// Method count minimum reversal for` `    ``// making an expression balanced.` `    ``// Returns -1 if expression cannot be balanced` `    ``public` `static` `int` `countMinReversals(``string` `expr)` `    ``{` `        ``int` `len = expr.Length;`   `        ``// length of expression must be` `        ``// even to make it balanced by` `        ``// using reversals.` `        ``if` `(len % 2 != 0) {` `            ``return` `-1;` `        ``}`   `        ``// After this loop, stack contains` `        ``// unbalanced part of expression,` `        ``// i.e., expression of the form "}}..}{{..{"` `        ``Stack<``char``> s = ``new` `Stack<``char``>();`   `        ``for` `(``int` `i = 0; i < len; i++) {` `            ``char` `c = expr[i];` `            ``if` `(c == ``'}'` `&& s.Count > 0) {` `                ``if` `(s.Peek() == ``'{'``) {` `                    ``s.Pop();` `                ``}` `                ``else` `{` `                    ``s.Push(c);` `                ``}` `            ``}` `            ``else` `{` `                ``s.Push(c);` `            ``}` `        ``}`   `        ``// Length of the reduced expression` `        ``// red_len = (m+n)` `        ``int` `red_len = s.Count;`   `        ``// count opening brackets at` `        ``// the end of stack` `        ``int` `n = 0;` `        ``while` `(s.Count > 0 && s.Peek() == ``'{'``) {` `            ``s.Pop();` `            ``n++;` `        ``}`   `        ``// return ceil(m/2) + ceil(n/2) which is` `        ``// actually equal to (m+n)/2 + n%2 when` `        ``// m+n is even.` `        ``return` `(red_len / 2 + n % 2);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``string` `expr = ``"}}{{"``;`   `        ``Console.WriteLine(countMinReversals(expr));` `    ``}` `}`   `// This code is contributed by Shrikant13`

Javascript

 ``

Output

```2

```

Time Complexity: O(n)
Auxiliary Space: O(n)

An another Intuitive Solution can solve this problem with same complexity.

The idea is to follow the algorithm used in Check if the parentheses is balanced or not. We follow this algorithm with a new condition when we find that the parentheses is not balanced.  This case arises when the stack is empty and we encounter a ‘ } ‘. In Check if the parentheses is balanced or not program we break the loop when we find that parentheses is not balanced but here we will reverse it to ‘ { ‘ and push it to the stack. While doing this, answer is incremented by 1.

Here, since we found a case of unbalanced expression the ‘ { ‘ must be changed in order to get a balanced expression. Also, changing this would be the most minimal way to get a balanced expression as it is a must condition to change it.

For example,  string = “}{{}}{}}” will be converted to “{{{}}{}}” and we get a balanced expression. There may arise a case where after doing this to the string we have some ‘{‘ left in the stack. For example,  string = “{}{{{{” will be converted to “{}{{{{” and there will be 4 ‘{‘ present in the stack which are not popped and are not balanced.

We can simply make it balanced by reversing the right half of the stack to ‘}’. Example: if stack has ‘ {{{{ ‘ left, we make it ‘ {{}} ‘ forming a balanced expression. Hence, answer gets updated by (stack size / 2). The case where the size of stack is odd, it is not possible to transform it to a balanced string.

Below is implementation of above idea:

C++

 `#include ` `using` `namespace` `std;` `#include `   `int` `countMinReversals(string str)` `{` `    ``// Step 1: Initialize a stack of char type and ans as 0.` `    ``stack<``char``> st;` `    ``int` `ans = 0;`   `    ``// Step 2: Run a loop for each character of the string` `    ``for` `(``int` `i = 0; i < str.size(); i++) {` `      `  `        ``// Step 2.1: If ' { ' encountered push it to the` `        ``// stack` `        ``if` `(str[i] == ``'{'``)` `            ``st.push(str[i]);` `        ``// Step 2.2: If ' } ' is encountered` `        ``else` `{` `            ``// Step 2.2.1: If stack has a '{' present for` `            ``// '}' encountered, pop from the stack.` `            ``if` `(!st.empty())` `                ``st.pop();` `            ``// Step 2.2.2: If stack is empty, change '}' to` `            ``// '{' and push it to stack and increment ans by` `            ``// 1` `            ``else` `{` `                ``st.push(``'{'``);` `                ``ans++;` `            ``}` `        ``}` `    ``}` `    ``// Step 3: if stack size is odd return -1.` `    ``if` `(st.size() % 2 != 0)` `        ``return` `-1;` `    ``// Step 4: Increment ans by ( stackSize/2 ).` `    ``ans += st.size() / 2;`   `    ``return` `ans;` `}`   `int` `main()` `{` `    ``string expr = ``"{{{{}}"``;` `    ``cout << countMinReversals(expr);` `    ``return` `0;` `}`

Java

 `/*package whatever //do not write package name here */`   `import` `java.io.*;` `import` `java.util.Stack;`   `class` `GFG {` `    ``static` `int` `countMinReversals(String str)` `    ``{` `        ``// Step 1: Initialize a stack of char type and ans as 0.` `        ``Stack st = ``new` `Stack();` `        ``int` `ans = ``0``;` `    `  `        ``// Step 2: Run a loop for each character of the string` `        ``for` `(``int` `i = ``0``; i < str.length(); i++) {` `          `  `            ``// Step 2.1: If ' { ' encountered push it to the` `            ``// stack` `            ``if` `(str.charAt(i) == ``'{'``)` `                ``st.add(str.charAt(i));` `            ``// Step 2.2: If ' } ' is encountered` `            ``else` `{` `                ``// Step 2.2.1: If stack has a '{' present for` `                ``// '}' encountered, pop from the stack.` `                ``if` `(!st.isEmpty())` `                    ``st.pop();` `              `  `                ``// Step 2.2.2: If stack is empty, change '}' to` `                ``// '{' and push it to stack and increment ans by` `                ``// 1` `                ``else` `{` `                    ``st.add(``'{'``);` `                    ``ans++;` `                ``}` `            ``}` `        ``}` `        ``// Step 3: if stack size is odd return -1.` `        ``if` `(st.size() % ``2` `!= ``0``)` `            ``return` `-``1``;` `      `  `        ``// Step 4: Increment ans by ( stackSize/2 ).` `        ``ans += st.size() / ``2``;` `    `  `        ``return` `ans;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``String expr = ``"{{{{}}"``;` `        ``System.out.println(countMinReversals(expr));` `    ``}` `}`   `// This code iscontributed by shinjanpatra.`

Python3

 `# Python code to implement the approach`   `def` `countMinReversals(``Str``):`   `    ``# Step 1: Initialize a stack of char type and ans as 0.` `    ``st ``=` `[]` `    ``ans ``=` `0`   `    ``# Step 2: Run a loop for each character of the String` `    ``for` `i ``in` `range``(``len``(``Str``)):` `        ``# Step 2.1: If ' { ' encountered push it to the` `        ``# stack` `        ``if` `(``Str``[i] ``=``=` `'{'``):` `            ``st.append(``Str``[i])` `        ``# Step 2.2: If ' } ' is encountered` `        ``else``:` `            ``# Step 2.2.1: If stack has a '{' present for` `            ``# '}' encountered, pop from the stack.` `            ``if` `(``len``(st)>``0``):` `                ``st.pop()` `            ``# Step 2.2.2: If stack is empty, change '}' to` `            ``# '{' and push it to stack and increment ans by` `            ``# 1` `            ``else``:` `                ``st.push(``'{'``)` `                ``ans ``+``=` `1` `            `  `    ``# Step 3: if stack size is odd return -1.` `    ``if` `(``len``(st) ``%` `2` `!``=` `0``):` `        ``return` `-``1` `    ``# Step 4: Increment ans by ( stackSize/2 ).` `    ``ans ``+``=` `len``(st) ``/``/` `2`   `    ``return` `ans`   `# driver code`   `expr ``=` `"{{{{}}"` `print``(countMinReversals(expr))`   `# This code is contributed by shinjanpatra`

C#

 `// C# Code to count minimum reversal for` `// making an expression balanced.` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{`   `  ``public` `static` `int` `countMinReversals(``string` `str)` `  ``{` `    ``// Step 1: Initialize a stack of char type and ans as 0.` `    ``Stack<``char``> st = ``new` `Stack<``char``>();` `    ``int` `ans = 0;`   `    ``// Step 2: Run a loop for each character of the string` `    ``for` `(``int` `i = 0; i < str.Length; i++) ` `    ``{` `      ``// Step 2.1: If ' { ' encountered push it to the` `      ``// stack` `      ``if` `(str[i] == ``'{'``)` `        ``st.Push(str[i]);` `      ``// Step 2.2: If ' } ' is encountered` `      ``else` `      ``{` `        ``// Step 2.2.1: If stack has a '{' present for` `        ``// '}' encountered, pop from the stack.` `        ``if` `(st.Count > 0)` `          ``st.Pop();`   `        ``// Step 2.2.2: If stack is empty, change '}' to` `        ``// '{' and push it to stack and increment ans by` `        ``// 1` `        ``else` `        ``{` `          ``st.Push(``'{'``);` `          ``ans++;` `        ``}` `      ``}` `    ``}` `    ``// Step 3: if stack size is odd return -1.` `    ``if` `(st.Count % 2 != 0)` `      ``return` `-1;`   `    ``// Step 4: Increment ans by ( stackSize/2 ).` `    ``ans += st.Count / 2;`   `    ``return` `ans;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``string` `expr = ``"{{{{}}"``;`   `    ``Console.WriteLine(countMinReversals(expr));` `  ``}` `}`   `// This code is contributed by kothavvsaakash`

Javascript

 ``

Output:

1

Time Complexity: O(n)
Auxiliary Space: O(n)

Another efficient solution solve the problem in O(1) i.e. constant space. Since the expression only contains one type of brackets, the idea is to maintain two variables to keep count of left bracket as well as right bracket as we did in Length of the longest valid substring. If the expression has balanced brackets, then we decrement left variable else we increment right variable. Then all we need to return is ceil(left/2) + ceil(right/2).

C++

 `// C++ program to find minimum number of` `// reversals required to balance an expression` `#include ` `using` `namespace` `std;`   `// Returns count of minimum reversals for making` `// expr balanced. Returns -1 if expr cannot be` `// balanced.` `int` `countMinReversals(string expr)` `{` `    ``int` `len = expr.length();`   `    ``// Expressions of odd lengths` `    ``// cannot be balanced` `    ``if` `(len % 2 != 0) {` `        ``return` `-1;` `    ``}` `    ``int` `left_brace = 0, right_brace = 0;` `    ``int` `ans;` `    ``for` `(``int` `i = 0; i < len; i++) {`   `        ``// If we find a left bracket then we simply` `        ``// increment the left bracket` `        ``if` `(expr[i] == ``'{'``) {` `            ``left_brace++;` `        ``}`   `        ``// Else if left bracket is 0 then we find` `        ``// unbalanced right bracket and increment` `        ``// right bracket or if the expression` `        ``// is balanced then we decrement left` `        ``else` `{` `            ``if` `(left_brace == 0) {` `                ``right_brace++;` `            ``}` `            ``else` `{` `                ``left_brace--;` `            ``}` `        ``}` `    ``}` `    ``ans = ``ceil``(left_brace / 2.0) + ``ceil``(right_brace / 2.0);` `    ``return` `ans;` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``string expr = ``"}}{{"``;` `    ``cout << countMinReversals(expr);` `    ``return` `0;` `}`

Java

 `// Java Code to count minimum reversal for` `// making an expression balanced.` `import` `java.util.*;` `public` `class` `GFG {`   `    ``// Method count minimum reversal for` `    ``// making an expression balanced.` `    ``// Returns -1 if expression cannot be balanced` `    ``static` `int` `countMinReversals(String expr)` `    ``{` `        ``int` `len = expr.length();` `        ``int` `ans;`   `        ``// Expressions of odd lengths` `        ``// cannot be balanced` `        ``if` `(len % ``2` `!= ``0``) {` `            ``return` `-``1``;` `        ``}` `        ``int` `left_brace = ``0``, right_brace = ``0``;` `        ``for` `(``int` `i = ``0``; i < len; i++) {` `            ``char` `ch = expr.charAt(i);`   `            ``// If we find a left bracket then we simply` `            ``// increment the left bracket` `            ``if` `(ch == ``'{'``) {` `                ``left_brace++;` `            ``}`   `            ``// Else if left bracket is 0 then we find` `            ``// unbalanced right bracket and increment` `            ``// right bracket or if the expression` `            ``// is balanced then we decrement left` `            ``else` `{` `                ``if` `(left_brace == ``0``) {` `                    ``right_brace++;` `                ``}` `                ``else` `{` `                    ``left_brace--;` `                ``}` `            ``}` `        ``}` `        ``ans = (``int``)(Math.ceil((``0.0` `+ left_brace) / ``2``)` `                    ``+ Math.ceil((``0.0` `+ right_brace) / ``2``));` `        ``return` `ans;` `    ``}`   `    ``// Driver method` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String expr = ``"}}{{"``;`   `        ``System.out.println(countMinReversals(expr));` `    ``}` `}`

Python3

 `# Python 3 program to find minimum number of` `# reversals required to balance an expression` `import` `math`   `# Returns count of minimum reversals for making` `# expr balanced. Returns -1 if expr cannot be` `# balanced.`     `def` `countMinReversals(expr):` `    ``length ``=` `len``(expr)`   `    ``# Expressions of odd lengths` `    ``# cannot be balanced` `    ``if` `(length ``%` `2` `!``=` `0``):` `        ``return` `-``1`   `    ``left_brace ``=` `0` `    ``right_brace ``=` `0`   `    ``for` `i ``in` `range``(length):`   `        ``# If we find a left bracket then we simply` `        ``# increment the left bracket` `        ``if` `(expr[i] ``=``=` `'{'``):` `            ``left_brace ``+``=` `1`   `        ``# Else if left bracket is 0 then we find` `        ``# unbalanced right bracket and increment` `        ``# right bracket or if the expression` `        ``# is balanced then we decrement left` `        ``else``:` `            ``if` `(left_brace ``=``=` `0``):` `                ``right_brace ``+``=` `1`   `            ``else``:` `                ``left_brace ``-``=` `1`   `    ``ans ``=` `math.ceil(left_brace ``/` `2``) ``+` `math.ceil(right_brace ``/` `2``)` `    ``return` `ans`     `# Driver program to test above function` `if` `__name__ ``=``=` `"__main__"``:`   `    ``expr ``=` `"}}{{"` `    ``print``(countMinReversals(expr))`   `    ``# This code is contributed by ukasp.`

C#

 `// C# Code to count minimum reversal for` `// making an expression balanced.` `using` `System;`   `public` `class` `GFG {`   `    ``// Method count minimum reversal for` `    ``// making an expression balanced.` `    ``// Returns -1 if expression cannot be balanced` `    ``static` `int` `countMinReversals(String expr)` `    ``{` `        ``int` `len = expr.Length;` `        ``int` `ans;`   `        ``// Expressions of odd lengths` `        ``// cannot be balanced` `        ``if` `(len % 2 != 0) {` `            ``return` `-1;` `        ``}` `        ``int` `left_brace = 0, right_brace = 0;` `        ``for` `(``int` `i = 0; i < len; i++) {` `            ``char` `ch = expr[i];`   `            ``// If we find a left bracket then we simply` `            ``// increment the left bracket` `            ``if` `(ch == ``'{'``) {` `                ``left_brace++;` `            ``}`   `            ``// Else if left bracket is 0 then we find` `            ``// unbalanced right bracket and increment` `            ``// right bracket or if the expression` `            ``// is balanced then we decrement left` `            ``else` `{` `                ``if` `(left_brace == 0) {` `                    ``right_brace++;` `                ``}` `                ``else` `{` `                    ``left_brace--;` `                ``}` `            ``}` `        ``}` `        ``ans = (``int``)(Math.Ceiling((0.0 + left_brace) / 2)` `                    ``+ Math.Ceiling((0.0 + right_brace)` `                                   ``/ 2));` `        ``return` `ans;` `    ``}`   `    ``// Driver method` `    ``public` `static` `void` `Main(String[] args)` `    ``{` `        ``String expr = ``"}}{{"``;`   `        ``Console.WriteLine(countMinReversals(expr));` `    ``}` `}`   `// This code is contributed by aashish1995.`

Javascript

 ``

Output

```2

```

Time Complexity: O(n)

Auxiliary Space: O(1)

Instead of maintaining two different variables for left brace and right brace, we can do it using a single temporary variable.

Traverse the array. For each ‘{‘ , increment the value of temp by 1 and for each ‘}’, if value of temp >0, then decrement the value of temp by 1 else, increment the value of result as well as temp by 1. At end, add half of the value of temp to the result.

Below is the implementation of above approach in C++.

C++

 `// C++ program to find minimum number of` `// reversals required to balance an expression` `#include ` `using` `namespace` `std;`   `// Returns count of minimum reversals for making` `// expr balanced. Returns -1 if expr cannot be` `// balanced.` `int` `countMinReversals(string s)` `{` `    ``int` `temp = 0, res = 0, n = s.size();` `    ``if` `(n % 2 != 0)` `        ``return` `-1;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(s[i] == ``'{'``)` `            ``temp++;` `        ``else` `{` `            ``if` `(temp == 0) {` `                ``res++;` `                ``temp++;` `            ``}` `            ``else` `                ``temp--;` `        ``}` `    ``}` `    ``if` `(temp > 0)` `        ``res += temp / 2;` `    ``return` `res;` `}`   `// Driver program to test above function` `int` `main()` `{` `    ``string expr = ``"}}{{"``;` `    ``cout << countMinReversals(expr);` `    ``return` `0;` `    ``// This code is contributed by Akansha Mittal` `}`

Java

 `// Java program to find minimum number of` `// reversals required to balance an expression` `import` `java.util.*;`   `class` `GFG {`   `    ``// Returns count of minimum reversals for making` `    ``// expr balanced. Returns -1 if expr cannot be` `    ``// balanced.` `    ``static` `int` `countMinReversals(String s)` `    ``{` `        ``int` `temp = ``0``, res = ``0``, n = s.length();` `        ``if` `(n % ``2` `!= ``0``)` `            ``return` `-``1``;` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``if` `(s.charAt(i) == ``'{'``)` `                ``temp++;` `            ``else` `{` `                ``if` `(temp == ``0``) {` `                    ``res++;` `                    ``temp++;` `                ``}` `                ``else` `                    ``temp--;` `            ``}` `        ``}` `        ``if` `(temp > ``0``)` `            ``res += temp / ``2``;` `        ``return` `res;` `    ``}`   `    ``// Driver program to test above function` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``String expr = ``"}}{{"``;` `        ``System.out.print(countMinReversals(expr));` `    ``}` `}`   `// This code is contributed by Rajput-Ji`

Python3

 `# Python program to find minimum number of` `# reversals required to balance an expression`   `# Returns count of minimum reversals for making` `# expr balanced. Returns -1 if expr cannot be` `# balanced.` `def` `countMinReversals(s):` `    ``temp, res, n ``=` `0``, ``0``, ``len``(s)`   `    ``if` `(n ``%` `2` `!``=` `0``):` `        ``return` `-``1` `    ``for` `i ``in` `range``(n):` `        ``if` `(s[i] ``=``=` `'{'``):` `            ``temp ``+``=` `1` `        ``else``:` `            ``if` `(temp ``=``=` `0``):` `                ``res ``+``=` `1` `                ``temp ``+``=` `1` `            ``else``:` `                ``temp ``-``=` `1`   `    ``if` `(temp > ``0``):` `        ``res ``+``=` `temp ``/``/` `2` `    ``return` `res`   `# Driver program to test above function` `expr ``=` `"}}{{"` `print``(countMinReversals(expr))`   `# This code is contributed by shinjanpatra`

C#

 `// C# program to find minimum number of` `// reversals required to balance an expression` `using` `System;` `class` `GFG {`   `    ``// Returns count of minimum reversals for making` `    ``// expr balanced. Returns -1 if expr cannot be` `    ``// balanced.` `    ``static` `int` `countMinReversals(``string` `s)` `    ``{` `        ``int` `temp = 0, res = 0, n = s.Length;` `        ``if` `(n % 2 != 0)` `            ``return` `-1;` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``if` `(s[i] == ``'{'``)` `                ``temp++;` `            ``else` `{` `                ``if` `(temp == 0) {` `                    ``res++;` `                    ``temp++;` `                ``}` `                ``else` `                    ``temp--;` `            ``}` `        ``}` `        ``if` `(temp > 0)` `            ``res += temp / 2;` `        ``return` `res;` `    ``}`   `    ``// Driver program to test above function` `    ``public` `static` `void` `Main()` `    ``{` `        ``string` `expr = ``"}}{{"``;` `        ``Console.Write(countMinReversals(expr));` `    ``}` `}`   `// This code is contributed by ukasp.`

Javascript

 ``

Output

```2

```

Time Complexity: O(n)

Auxiliary Space: O(1)

Thanks to Utkarsh Trivedi for suggesting above approach.

Previous
Next