


If the given string S = “ [[]]][ ”, the answer will be 1 as if we swap the last and second last character, the string will be balanced.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ denoting the number of characters present in string S.
The following line contains the string ‘S’.
For each test case, print ‘an integer corresponding to the minimum number of swaps required.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6.
S[i] = { ‘[’ , ‘]’}.
Time limit: 1 sec
In this approach, we will declare two pointers ‘i’ and ‘j’ to traverse the string. ‘i‘ will be pointing to the first character and ‘j’ will be pointing to the last character. We will store the number of unused opening brackets in variable ‘C’. We will iterate ‘i’ from left to right, if we find any opening bracket, we will increment ‘C’ to ‘C+1’. If we found a closing bracket, we will decrement ‘C’ to ‘C’-1 as one opening bracket will be used. If ‘C’ became -1, that implies the closing bracket should be swapped with an opening bracket. So, they will find the first opening bracket from the end using pointer ‘j’ and swap them and increment ‘ANS’ as ‘ANS+1’.
At last, we will return ‘ANS’ storing the minimum number of swaps required.
In this approach, we will traverse the whole string ‘S’ and find the number of opening brackets that are not matched with a closing bracket. Let that number is ‘X’, so the number of swaps required is (X+1)/2, as we have seen in approach-1 that one swap can reduce the number of unused opening brackets by 2.
For example if S = “]]]][[[[“ and here the number of unused opening brackets is 4.If we swap the first and last character of the string, the resultant string will be ‘[]]][[[]’ whose number of unused opening brackets is2.
At last, we will return (‘X’+1)/2.