 # Minimum number of bracket reversals needed to make an expression balanced

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`

One simple observation is, the string can be balanced only if total number of brackets is even (there must be equal no of '{' and '}')

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).

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++ 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;
}

Output:

`2`

Time Complexity: O(n)
Auxiliary Space: O(n) #### More Articles of M Mounika:

Name Views Likes
C++ Segmented Sieve (Print Primes In a Range) 163 0
C++ Sieve Of Erastosthenes 136 0
C++ Gold Mine Problem 295 0
C++ Merge K Sorted Arrays 117 0
C++ K Centers Problem 240 0
C++ Find Nth Catalan Number 311 0
C++ Inplace Rotate square matrix by 90 degrees 286 0
C++ Find Non Repeating Elements in Array 87 0
C++ Merge Two Binary Trees 121 0
C++ Sum of Numbers From Root To Leaf Paths 89 0
C++ Meta Strings 92 0
C++ Flood Fill Algorithm 402 0
C++ smallest substring with maximum distinct characters 200 0
C++ Smallest window with all characters in string 94 0
C++ Minimum Removal of Characters from string to make its permutation as palindrome 87 0
C++ Minimum characters added at front of string in palindrome conversion 70 0
C++ Number of Bracket Reversals needed to make expression Balanced 73 0
C++ String to Palindrome with Append Function 83 0
C++ WildCard pattern matching 76 0
C++ Anagram substring Search 72 0
C++ Manachars Algorithm 74 0
C++ Search String in Grid 83 0
C++ String Matching(Z Algorithm) 67 0
C++ String Matching(Naive Algorithm) 114 0
C++ String Matching(KMP Algorithm) 141 0
C++ Remove Duplicates From String 111 0
C++ Basics of String Manipulation 85 1
C++ Disjoint Data Structure Cycle Detection 87 0
C++ Problem On Disjoint Data Structures 95 0
C++ Disjoint Data Structures Part3 79 0
Disjoint Data Structures Part2 91 0
Disjoint Data Structures 93 1
C++ Segment Trees 321 2
C++ Trie Cost of Data 291 1
C++ Trie Datastructure 279 1
C++ Greedy Approach Minimum number of coins 526 0
C++ Greedy Approach Maximum height Pyramid 329 1
C++ Greedy Approach String lexicographically largest subsequence 247 0
C++ Greedy Approach Lexicographically largest subsequence 364 0
C++ Greedy Approach Prims MST 398 1
C++ Greedy Approach Krushkals MST 458 1
C++ Greedy Approach N-array maximum sum 334 1
C++ Greedy Approach Policemen Catch Thieves 563 1
C++ Greedy Approach Maximum product Subset 546 1
C++ Greedy Approach Minimum Product Subset 349 1
C++ Greedy Approach Fractional Knapsack 737 1
C++ Greedy Approach-Activity Selection Problem 745 1
C++ Greedy Approach-Egyptian Fractions 640 0
C++ Greedy Approach-Huffman Codes 1031 1
C++ Introduction to Greedy Approach 955 2