


Here are some examples of balanced BRACKETS "(())", "()()", "(())()".
The first line of input contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains one integer ‘N’ representing the number opening (or closing) brackets.
The second line of each test case contains a string‘ BRACKETS’ of length '2*N'.
For each test case, print the minimum possible swaps required to make string ‘BRACKETS’ balanced.
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’ <= 100
1 <= ‘N’ <= 5000
‘BRACKETS’[i]’ = ‘(‘ or ‘)’
Time Limit: 1 second
We apply a greedy approach to balance ‘BRACKETS’. If the first ‘X’ characters form a balanced string, then we neglect these characters. And we maintain a ‘count’ variable. If we encounter an open ‘(‘ bracket then we increase our ‘count’ by ‘1’ else we decrease the ‘count’ by ‘1’. If the ‘count’ is negative, then we start balancing ‘BRACKETS’.
For balancing ‘BRACKETS’, we first store the current position say ‘i’, and then find the position of next ‘(‘ say ‘j’. We then swap the characters present at these positions. We also add ‘j’ - ‘i’ in our answer. We repeat this process until ‘BRACKETS’ is not balanced. In the end, we return our required answer.
Here is the algorithm :
In this approach, we make a list ‘posOfLeftBracket’ and store all positions of ‘(‘. We then take the variable ‘i’ which is used to indicate the next position of ‘(‘. We also maintain a ‘count’ variable and update it as mentioned in the previous approach. If the ‘count’ is negative, then we have to start balancing the string.
We swap the current index and ‘posOfLeftBracket[i]’ and add ‘posOfLeftBracket[i]’ - ‘i’ in ‘minSwaps’. We then reset the ‘count’ to ‘1’ and ‘i’ to ‘i+1’.
Here is the complete algorithm :