Count the Reversals | Practice | GeeksforGeeks

Given a string S consisting of only opening and closing curly brackets '{' and '}', find out the minimum number of reversals required to convert the string into a balanced expression.
A reversal means changing '{' to '}' or vice-versa.
Example 1:
Input:
S = "}{{}}{{{"
Output: 3
Explanation: One way to balance is:
"{{{}}{}}". There is no balanced sequence
that can be formed in lesser reversals.

â€‹Example 2:
Input: 
S = "{{}{{{}{{}}{{"
Output: -1
Explanation: There's no way we can balance
this sequence of braces.

Your Task:
You don't need to read input or print anything. Your task is to complete the function countRev() which takes the string S as input parameter and returns the minimum number of reversals required to balance the bracket sequence. If balancing is not possible, return -1. 
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ |S| ≤ 105
 
0
himanshukug19cs2 weeks ago
java solution
    Stack<Character> st = new Stack<>();       int count=0;       int ans=0;       for(int i=0;i<s.length();i++){           if(st.empty()){               if(s.charAt(i)=='}'){                  ans++;}                                    st.push('{');           }else{               if(s.charAt(i)=='}')                    st.pop();               else{                   st.push('{');               }                }       }       if(st.size()%2==0){      ans+=st.size()/2;      return ans;       }       return -1;          
0
hanumanmanyam8374 weeks ago
class Sol
{
    int countRev (String s)
    {
        // your code here 
        Stack<Character>st=new Stack<>();
        int ans=0;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='{')
            {
                st.push(s.charAt(i));
            }
            else
            {
                if(st.isEmpty())
                {
                    st.push('{');
                    ans++;
                }
                else
                {
                    st.pop();
                }
            }
        }
        if(st.size()%2==0)
        {
            ans=(st.size()/2)+ans;
            return ans;
        }
        return -1;
        
    }
}
0
amarrajsmart1971 month ago
C++ CODE   time taken=0.1 sec out of assigned 2.0 sec 
 
 stack<char>st;   int ans=0;   for(int i=0;i<s.length();i++)   {       if(s[i]=='{')       {           st.push(s[i]);       }       else       {           if(st.empty())           {               st.push(s[i]);               ans++;           }           else           {              st.pop();            }       }   }   if(st.size()%2==0){   ans+=st.size()/2;   return ans;}elsereturn -1;}
0
ksandeep27071 month ago
C++ CODE:-
int countRev (string s)
{
    stack<char> st;
    int ans=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='{')
          st.push(s[i]);
        else
        {
            if(st.empty())
               { st.push('{');ans++;}
            else
                st.pop();
        }
    }
    if(st.size()%2==0)
    return st.size()/2+ans;
    else
    return -1;
}
0
officialshivaji0071 month ago
int countRev (string s){   // your code here   int n = s.size();      if(n&1) return -1;     stack<char> st;   int rev = 0;   for(auto ch : s){       if(ch == '{'){           st.push('{');       }else{           if(st.size()==0) {               rev++;               st.push('{');           }           else{               st.pop();           }       }   }         rev += st.size()/2;      return rev;}
0
shubham55jha11 month ago
JAVA
		// your code here   
        int n = s.length();
        if(n % 2 != 0) return -1;
        ArrayDeque<Character> q = new ArrayDeque<>();
        for(int i = 0; i < n; i++){
            char ch = s.charAt(i);
            if(q.isEmpty() || ch == '{') q.offer(ch);
            else if(q.peekLast() == '{') q.pollLast();
            else q.offer(ch);
        }
        int res = 0;
        while(!q.isEmpty()){
            if(q.pop() == q.pop()) res++;
            else res += 2;
        }
        return res;
+1
praveenprakash4392 months ago
int countRev (string s)
{
    stack<char>st;
    int ans=0;
    for(int i=0;i<s.size();++i)
    {
        if(st.empty())
          st.push(s[i]);
        else if(st.top()=='{' and s[i]=='}')
          st.pop();
        else
          st.push(s[i]);
    }
    if(st.size()%2!=0)
      return -1;
    while(!st.empty()){
        char temp1=st.top();st.pop();
        char temp2=st.top();st.pop();
        
        if(temp1==temp2)
          ans++;
        else
          ans+=2;
    }
    
    return ans;
    
}
0
gujjulassr2 months ago
Total Time Taken:
0.6/1.7
 
class Sol{   int countRev (String str)   {       // your code here          Stack<Character> s=new Stack<Character>();       for(int i=0;i<str.length();i++){           if(str.charAt(i)=='}'){               if(s.isEmpty()){                   s.push(str.charAt(i));               }else{                   if(s.peek()!=str.charAt(i)){                       s.pop();                   }else{                       s.push(str.charAt(i));                   }               }           }else{               s.push(str.charAt(i));           }       }      if(s.size()%2!=0){          return -1;      }      int co=0;      int cc=0;      while(!s.isEmpty()){          if(s.peek()=='{'){              co++;          }else{              cc++;          }          s.pop();      }      return (co%2)+(cc%2)+(co/2)+(cc/2);   }}
0
uphaarkamal20032 months ago

int countRev (string s)
{
    // your code here
    int n = s.size();
    if(n%2==1)
    return -1;
    stack<int> st;
    int count=0;
    for(int i=0 ; i<s.size() ; i++){
        if(st.empty() || s[i]=='{'){
            st.push(s[i]);
            continue;
        }
        char ch = st.top();
        if(ch=='{'){
            st.pop();
        }
        else
        st.push(s[i]);
    }
    while(!st.empty()){
        char ch1=st.top();
        st.pop();
        char ch2=st.top();
        st.pop();
        if((ch1=='{' && ch2=='{') || (ch1=='}' && ch2=='}'))
        count++;
        else
        count += 2;
    }
    return count;
}

+1
manishkumar250319992 months ago
int countRev (string s){ if(s.length()%2!=0)   return -1;   int l=0,r=0;  for(int i=0;i<s.length();i++)  {      if(s[i]=='{')        l++;        else        {            if(l==0)               r++;               else               l--;        }  }   return ceil(l/2.0)+ceil(r/2.0);
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.