Open In App

Minimum number of bracket reversals needed to make an expression balanced | Set – 2

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. The task is to 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 : 3
The balanced expression is "{{{}}{}}"


 


The solution discussed in previous post requires O(n) extra space. The problem can be solved using constant space. 
The idea is to use two variables open and close where, open represents number of unbalanced opening brackets and close represents number of unbalanced close brackets. 
Traverse the string and if current character is an opening bracket increment open. If current character is a closing bracket then check if there are unbalanced opening brackets(open > 0). If yes then decrement open else increment close as this bracket is unbalanced.
Below is the implementation of above approach: 
 

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();

    // length of expression must be even to make
    // it balanced by using reversals.
    if (len % 2)
        return -1;

    // To store number of reversals required.
    int ans = 0;

    int i;

    // To store number of unbalanced opening brackets.
    int open = 0;

    // To store number of unbalanced closing brackets.
    int close = 0;

    for (i = 0; i < len; i++) {

        // If current bracket is open then increment
        // open count.
        if (expr[i] == '{')
            open++;

        // If current bracket is close, check if it
        // balances opening bracket. If yes then
        // decrement count of unbalanced opening
        // bracket else increment count of
        // closing bracket.
        else {
            if (!open)
                close++;
            else
                open--;
        }
    }

    ans = (close / 2) + (open / 2);

    // For the case: "}{" or when one closing and
    // one opening bracket remains for pairing, then
    // both need to be reversed.
    close %= 2;
    open %= 2;
    if (close)
        ans += 2;

    return ans;
}

// Driver Code
int main()
{
    string expr = "}}{{";

    cout << countMinReversals(expr);

    return 0;
}
Java
// Java program to find minimum number of 
// reversals required to balance an expression 
class GFG
{

// Returns count of minimum reversals for making 
// expr balanced. Returns -1 if expr 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; 

    // To store number of reversals required. 
    int ans = 0; 

    int i; 

    // To store number of unbalanced opening brackets. 
    int open = 0; 

    // To store number of unbalanced closing brackets. 
    int close = 0; 

    for (i = 0; i < len; i++)
    { 

        // If current bracket is open then increment 
        // open count. 
        if (expr.charAt(i) == '{') 
            open++; 

        // If current bracket is close, check if it 
        // balances opening bracket. If yes then 
        // decrement count of unbalanced opening 
        // bracket else increment count of 
        // closing bracket. 
        else 
        { 
            if (open == 0) 
                close++; 
            else
                open--; 
        } 
    } 

    ans = (close / 2) + (open / 2); 

    // For the case: "}{" or when one closing and 
    // one opening bracket remains for pairing, then 
    // both need to be reversed. 
    close %= 2; 
    open %= 2; 
    if (close != 0) 
        ans += 2; 

    return ans; 
} 

// Driver Code 
public static void main(String args[])
{ 
    String expr = "}}{{"; 

    System.out.println(countMinReversals(expr)); 
} 
}

// This code is contributed by Arnab Kundu
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):

    length = len(expr)

    # length of expression must be even to 
    # make it balanced by using reversals.
    if length % 2:
        return -1

    # To store number of reversals required.
    ans = 0

    # To store number of unbalanced
    # opening brackets.
    open = 0

    # To store number of unbalanced 
    # closing brackets.
    close = 0

    for i in range(0, length): 

        # If current bracket is open 
        # then increment open count.
        if expr[i] == "":
            open += 1

        # If current bracket is close, check if it
        # balances opening bracket. If yes then
        # decrement count of unbalanced opening
        # bracket else increment count of
        # closing bracket.
        else:
            if not open:
                close += 1
            else:
                open -= 1
        
    ans = (close // 2) + (open // 2)

    # For the case: "" or when one closing 
    # and one opening bracket remains for 
    # pairing, then both need to be reversed.
    close %= 2
    open %= 2
    
    if close > 0:
        ans += 2

    return ans

# Driver Code
if __name__ == "__main__":

    expr = "}}{{"
    print(countMinReversals(expr))

# This code is contributed by Rituraj Jain
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 expr) 
{ 
    int len = expr.Length; 

    // length of expression must be even to make 
    // it balanced by using reversals. 
    if (len % 2 != 0) 
        return -1; 

    // To store number of reversals required. 
    int ans = 0; 

    int i; 

    // To store number of unbalanced opening brackets. 
    int open = 0; 

    // To store number of unbalanced closing brackets. 
    int close = 0; 

    for (i = 0; i < len; i++)
    { 

        // If current bracket is open then increment 
        // open count. 
        if (expr[i] == '{') 
            open++; 

        // If current bracket is close, check if it 
        // balances opening bracket. If yes then 
        // decrement count of unbalanced opening 
        // bracket else increment count of 
        // closing bracket. 
        else
        { 
            if (open == 0) 
                close++; 
            else
                open--; 
        } 
    } 

    ans = (close / 2) + (open / 2); 

    // For the case: "}{" or when one closing and 
    // one opening bracket remains for pairing, then 
    // both need to be reversed. 
    close %= 2; 
    open %= 2; 
    if (close != 0) 
        ans += 2; 

    return ans; 
} 

// Driver Code 
public static void Main(String []args)
{ 
    String expr = "}}{{"; 

    Console.WriteLine(countMinReversals(expr)); 
} 
}

// This code contributed by Rajput-Ji
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)
{
    var len = expr.length;

    // length of expression must be even to make
    // it balanced by using reversals.
    if (len % 2)
        return -1;

    // To store number of reversals required.
    var ans = 0;

    var i;

    // To store number of unbalanced opening brackets.
    var open = 0;

    // To store number of unbalanced closing brackets.
    var close = 0;

    for (i = 0; i < len; i++) {

        // If current bracket is open then increment
        // open count.
        if (expr[i] == '{')
            open++;

        // If current bracket is close, check if it
        // balances opening bracket. If yes then
        // decrement count of unbalanced opening
        // bracket else increment count of
        // closing bracket.
        else {
            if (!open)
                close++;
            else
                open--;
        }
    }

    ans = (close / 2) + (open / 2);

    // For the case: "}{" or when one closing and
    // one opening bracket remains for pairing, then
    // both need to be reversed.
    close %= 2;
    open %= 2;
    if (close)
        ans += 2;

    return ans;
}

// Driver Code
var expr = "}}{{";
document.write( countMinReversals(expr));

// This code is contributed by noob2000.
</script>

Output
2

Time Complexity: O(N), where N is the length of the string. 
Auxiliary Space: O(1)

Stack Based Appraoch :

We can solve the above problem using Stack to keeping tracks as following :

  • Use a stack to keep the track of brackets
  • Then, Iterate through the expression
  • If { is encountered then push it into the stack
  • If } is encountered then check the top of the stack
    1. If it is { then pop it from the stack
    2. If it is not { it means there is mismatch so push } onto the stack.
  • After completing the iteration the stack may contain unmatched brackets
  • Count the number of unmatched { and } on the stack

Below is the implementation of above approach: 

Python
def min_reversals_to_balance(exp):
    stack = []  # Initialize an empty stack to keep track of unmatched brackets
    for bracket in exp:
        if bracket == '{':
            stack.append(bracket)  
        elif bracket == '}':
            if stack and stack[-1] == '{':
                stack.pop()  # If '}' matches with the top of the stack, pop the corresponding '{'
            else:
                stack.append(bracket)  # Otherwise, push '}' onto the stack as it's unmatched
    
    # Count the number of unmatched '{' and '}'
    unmatched_open = sum(1 for b in stack if b == '{')
    unmatched_close = sum(1 for b in stack if b == '}')
    
    # Calculate the minimum number of reversals required
    # Each pair of unmatched '{' and '}' requires one reversal, plus any single unmatched brackets
    reversals = (unmatched_open + 1) // 2 + (unmatched_close + 1) // 2
    
    return reversals

exp1 = "}{"
exp2 = "}{{}}{{{"

print(min_reversals_to_balance(exp1))
print(min_reversals_to_balance(exp2))

Output:

2
3

Time Complexity: O(n), Where n is the length of the expression. 

Auxiliary Space: O(n)












Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads