Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimum number of bracket reversals needed to make an expression balanced

  • Difficulty Level : Medium
  • Last Updated : 27 Oct, 2021

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: 2
We 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 reversals

Input:  exp = "{{{{"
Output: 2 

Input:  exp = "{{{{}}"
Output: 1 

Input:  exp = "}{{}}{{{"
Output: 3

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. Time complexity of this solution is O(2n). 

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!

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 ⌈m/2⌉ + ⌈n/2⌉ 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<bits/stdc++.h>
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<Character> 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




<script>
  
        // JavaScript 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.
        function countMinReversals(expr) {
            let len = expr.length;
 
            // Expressions of odd lengths
            // cannot be balanced
            if (len % 2)
                return -1;
 
            // After this loop, stack contains unbalanced
            // part of expression, i.e., expression of the
            // form "}}..}{{..{"
            var s = new Array();
            for (let i = 0; i < len; i++) {
                if (expr[i] == '}' && !s.length == 0) {
                    if (s[s.length - 1] == '{')
                        s.pop();
                    else
                        s.push(expr[i]);
                }
                else
                    s.push(expr[i]);
            }
 
            // Length of the reduced expression
            // red_len = (m+n)
            let red_len = s.length;
 
            // count opening brackets at the end of
            // stack
            let n = 0;
            while (!s.length == 0 && s[s.length - 1] == '{') {
                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
 
        let expr = "}}{{";
        document.write(countMinReversals(expr));
 
</script>
Output



2

Output: 

2

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 <bits/stdc++.h>
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




  <script>
   
// JavaScript 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.
function countMinReversals( expr)
{
    let len = expr.length;
   
    // Expressions of odd lengths
    // cannot be balanced
    if (len % 2 != 0) {
        return -1;
    }
    let left_brace = 0, right_brace = 0;
    let ans;
    for (let 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 = Math.ceil(left_brace / 2) + Math.ceil(right_brace / 2);
    return ans;
}
 
// Driver program to test above function
 
    let expr = "}}{{";
    document.write(countMinReversals(expr));
 
</script>
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 <bits/stdc++.h>
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
}
Output
2

Time Complexity: O(n)

Auxiliary Space: O(1)

Thanks to Utkarsh Trivedi for suggesting above approach.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :