Minimum Swaps for Bracket Balancing
Easy Accuracy: 30.84% Submissions: 3121 Points: 2

You are given a string 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.


The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N denoting the length of the string.

The second line of each test case contains the string consisting of '[' and ']'.


Print the minimum number of swaps to make the string balanced for each test case in a new line.


1<= T <=100

1<= N <=100000



Input  : []][][
Output : 2
First swap: Position 3 and 4
Second swap: Position 5 and 6

Input  : [[][]]
Output : 0
String is already balanced.

to report an issue on this page.


We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?


All Submissions

My Submissions:

Login to access your submissions.