Minimum Swaps for Bracket Balancing | Practice | GeeksforGeeks

You are given a string S of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balanced.
Note - Strings S1 and S2 can be empty.
 
Example 1:
Input  : []][][
Output : 2
Explanation :
First swap: Position 3 and 4
[][]][
Second swap: Position 5 and 6
[][][]


 
Example 2:
Input : [[][]]
Output : 0 
Explanation:
String is already balanced.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function minimumNumberOfSwaps() which takes the string S and return minimum number of operations required to balance the bracket sequence.
 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
 
Constraints:
1<=|S|<=100000
 
0
gulshankumaransh9796 hours ago
PYTHON###
class Solution:   def minimumNumberOfSwaps(self,S):       chars = S       countLeft = 0       countRight = 0       swap = 0       imbalance = 0           for i in range(len(chars)):           if chars[i] == '[':               countLeft += 1               if imbalance > 0:                   swap += imbalance                   imbalance -= 1           elif chars[i] == ']':               countRight += 1               imbalance = (countRight - countLeft)       return swap
0
shilsoumyadip2 weeks ago
 int minimumNumberOfSwaps(string S){       // code here       int c =0;       int swap =0;              for(int i =0;i<S.length();i++)       {           if(S[i] ==']')           {               c++;                              if(c > 0)               swap += c;           }           else           {               c--;           }       }       return swap;   }
0
govidkrishna772 weeks ago
class Solution{   static int minimumNumberOfSwaps(String S){       int swap=0;       int count=0;       for(int i=0;i<S.length();i++){           if(S.charAt(i)=='['){               count--;           }           if(S.charAt(i)==']'){               count++;               if(count>0){                   swap+=count;               }           }       }       return swap;       // code here   }}
0
anubhavnegi54
This comment was deleted.
0
badgujarsachin831 month ago
 int minimumNumberOfSwaps(string S){
        // code here 
        int swap=0,x=0;
        for(int i=0;i<S.size();i++){
            if(S[i]=='['){
                x--;
            }else{
                x++;
                if(x>0){
                    swap+=x;
                }
            }
        }
        return swap;
    }
0
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.0 / 1.1 sec
 
int minimumNumberOfSwaps(string s){       int n = s.length();       int open = 0, close = 0, fault = 0;       int swaps = 0;       for(int i = 0; i < n; i++){           if(s[i] == ']'){               close++;               fault = close - open;           }           else{               open++;               if(fault > 0){                   swaps += fault;                   fault--;               }           }       }       return (swaps);   }
+1
2020010432 months ago
//Easy solution
int minimumNumberOfSwaps(string S){       int ans=0,c=0,n=S.length();       for(int i=0;i<n;i++){           if(S[i]=='[')c++;           else{               c--;               if(c<0)ans-=c;           }       }       return ans+c;   }
+1
manishmaheshwari81332 months ago
JAVA CODE
TC: O(N)
SC=O(1)
class Solution{
    static int minimumNumberOfSwaps(String S){
        int open=0,close=0,fault=0,swap=0;
        for(int i=0;i<S.length();i++){
            
            if(S.charAt(i)==']'){
                close++;
                fault=close-open;
            }else {
                open++;
                if(fault>0){
                    swap+=fault;
                    fault --;
                }
            }
        }
        return swap;
    }
}
0
absaarali15482 months ago
int minimumNumberOfSwaps(string S){       int x = 0 ,swaps = 0 , n = S.length();       for(int i = 0 ; i<n ; i++)       {           if(S[i]=='[')               x--;           else           {               x++;               if(x>0)                   swaps+=x;           }       }       return swaps;   }
0
sinhaabhijeet92 months ago
int minimumNumberOfSwaps(string S){       // code here       int size = S.size();       stack<char> t;       int count= 0;      for(int i = 0;i<size;i++)   {       if(S[i] == '[')       {           if(t.size() == 0)           {               t.push(S[i]);               continue;           }           else if(t.top()=='[')           {               t.push(S[i]);           }           else if(t.top()==']')           {               count+= t.size();               t.pop();                          }                      }              else if(S[i]==']')       {           if(t.size() == 0)           {               t.push(S[i]);               continue;           }           else if(t.top()=='[')           {               t.pop();           }           else if(t.top()==']')           {               t.push(S[i]);           }                  }          }   return count;   }
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.