Minimum Swaps for Bracket Balancing
Submissions: 1467   Accuracy:

28.72%

  Difficulty: Easy   Marks: 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.

Input:

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 ']'.

Output:

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


Constraints:

1<= T <=100

1<= N <=100000

 

Example:

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

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

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Sujnesh Mishra
Author: sujnesh


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.