-2

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

…. python `` a=['}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{']

for elem in a:
    sol=0
    stack=[]
 #stack.append(elem[i])
    i=0
    while i<len(elem)-1:
        if elem[i]=='{' and elem[i+1]=='{':
            stack.append(elem[i])
            stack.append(elem[i+1])
            sol+=1
        elif elem[i]=='}' and elem[i+1]=='{':
            if len(stack)!=0:
                if stack[-1]=='{':
                    stack.pop()
                    stack.append(elem[i+1])

                else:
                    stack.append(elem[i])
                    stack.append(elem[i+1])
                    sol+=1
            else:  
                stack.append(elem[i])
            ``  stack.append(elem[i+1])
                sol+=2
        elif elem[i]=='}' and elem[i+1]=='}':
            if len(stack)!=0:
                if stack[-1]=='{' and stack[-2]=='{':
                    stack.pop()
                    stack.pop()
                    sol-=1
                elif stack[-1]=='{' and stack[-2]=='}':
                    stack.pop()
                    stack.append(elem[i+1])
                else:
                    stack.append(elem[i])
                    stack.append(elem[i+1])
                    sol+=1
            else:
                stack.append(elem[i])
                stack.append(elem[i+1])
                sol+=1
        i+=2
    print(sol)

….

expected 5 output 6

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54
Lakshya
  • 1
  • 2

3 Answers3

1

I have tried to solve your question based upon the number of opened brackets and inversions required for the string expression, to count the minimum number of bracket reversals.

Python code for the same is given below:

def cal_rev(exp):
    if len(exp) % 2:
        return -1
    open = 0
    invert = 0
    for i in exp:
        if i == '{':
            open += 1
        else:
            if open:
                open -= 1
            else:
                open = 1
                invert += 1
    print(invert + open/2)


if __name__ == '__main__':
    expr = "}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{"
    cal_rev(expr)
Kshitij
  • 11
  • 1
0

Using Python


def countBracketReversals(string):
    if(len(string) == 0):
        return 0
    if(len(string)%2 != 0):
        return -1
    s = []
    for char in string:
        if char == '{':
            s.append(char)
        else:
            if(len(s) > 0 and s[-1] == '{'):
                s.pop()
            else:
                s.append(char)
    count = 0
    while(len(s) != 0):
        c1 = s.pop()
        c2 = s.pop()
        if c1!=c2:
            count+=2
        else:
            count+=1
    return count
string = input()
ans = countBracketReversals(string)
print(ans)

Output

}{}{}{}}}{{{{{}{}{}}{{}{}{}}{{}}{{
5

Link: https://www.svastikkka.com/2022/07/minimum-bracket-reversal.html

Manshu Sharma
  • 83
  • 1
  • 8
-1

You can find the answer to your question using this link. This link provides different approaches to solve the above problem along with c, java and python codes.

The best approach used in the link is simple and it involves following steps.

  1. Remove the balanced part of the string in first traversal and keep only the unbalanced part in stack.

  2. Then you are only left with string of type }}}...}{...{{{ in your stack.

  3. Let the count of } be m and count of { be n.

  4. Minimum number of reversals will be ceil(m/2) + ceil(n/2).

Python code is below:

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) 

Time complexity: O(n)

Enjoy!

Adarsh Anurag
  • 630
  • 5
  • 17
  • Can you please explain what's the logic behind `# return ceil(m/2) + ceil(n/2)` – Neeraj Jain Jul 02 '20 at 13:47
  • First of all, there needs to even number of brackets. If the number of brackets are not even, they cannot be balanced. After removing the balance part we are left with }}}....}}}{{{..{{{ this part. The length of this part will also be even. So m and n are both even or both odd. If m and n are both even, then the answer is m/2 + n/2. But if m and n are both odd, (for example }}}}}{{{ m = 5 and n = 3), then minimal reversals required will be ceil(5/2) + ceil(3/2) = 3+2 = 5. i.e. {{}}{}{}. In order to balance the middle }{, we use ceil @NeerajJain – Adarsh Anurag Jul 02 '20 at 18:52