


“{}{}”, “{{}}”, “{{}{}}” are valid strings while “}{}”, “{}}{{}”, “{{}}}{“ are not valid strings.
Minimum operations to make ‘STR’ = “{{“ valid is 1.
In one operation, we can convert ‘{’ at index ‘1’ (0-based indexing) to ‘}’. The ‘STR’ now becomes "{}" which is a valid string.
Return -1 if it is impossible to make ‘STR’ valid.
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The only line of each test case contains a string 'STR'.
For each test case, print the minimum cost needed to make ‘STR’ valid.
Print -1 if it is impossible to make ‘STR’ valid.
Print the output of each test case in a separate line.
You are not required to print the expected output, it has already been taken care of. Just implement the function.
1 <= T <= 100
0 <= |STR| <= 10^5
STR[i] = ‘{’ or ‘}’
Time Limit: 1 sec
The idea for this approach is to consider every bracket and then recursively count the number of reversals.
We will have only two cases: either a bracket remains the same or converted to another. If we get a valid string, we will count the cost and update the minimum cost so far.
Algorithm:
Initialize a variable ‘minCostSoFar’ to maximum possible value, and call helper function minCostUtil which is a recursive function having parameters ‘index’ that denotes the current index in the ‘STR’, ‘currCost’ which is the cost to make string valid till ‘index’ and ‘minCostSoFar’ which denotes the minimum cost so far to make ‘STR’ valid.
Implementation of minCostUtil is as follows :
We can use a stack to solve this problem. This approach aims to first remove valid parts of ‘STR’. For example, if ‘STR’ is “}{{}{” we will remove the valid part “{}” from ‘STR’ and the remaining part will be “}{{”. If we observe, we can notice that after removing the valid part from ‘STR’, we will always get a string like “}}{{…{“, a string that has 0 or more number of ‘}’ comes before, 0 or more numbers of ‘{’. Now let the number of ‘{’ is ‘p’ and the number of ‘}’ is ‘q'. Then we will need (‘p’ + 1) / 2 + (‘q’ + 1 / 2) reversals.
We can remove the valid part using the stack.
The algorithm for this approach is the following: