


1. It is an empty string, it contains lowercase alphabets only, or
2. It can be written as (S), where ‘S’ is the valid string.
3. It can be written as AB (‘A’ concatenated with ‘B’), where ‘A’ and ‘B’ are valid strings.
Let string be: “co(di()ng”
The valid string can be: “co(di)ng” or “codi()ng”.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains a string ‘S’.
For each test case, print a valid string. There are multiple answers possible, you may print any of them.
Print 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 <= |S| <= 10^5
Where |S| represents the length of the string ‘S’.
Time Limit: 1 sec
The basic idea is to remove the brackets of the string for all the possibilities and check for the string validity. We keep the count for all the valid strings and print, which takes minimum deletion to make the string valid.
If the current character is “)” or “(“ we have two choices with us:
HELPER(‘S’, ‘CNT’, ‘TEMP’, ‘CURR’, ’valStr’) (where ‘S’ is the given string, ‘CNT’ is to store the minimum number of deletions, ‘TEMP’ is the number of deletions done till the current string, and ‘CURR’ is the current string).
isValid(‘CURR’) (where ‘CURR’ is the current string).
The basic idea is to store the indices of the brackets that are not balanced in a stack. We also maintain a hashmap to store the indices that need to be removed. We traverse the string and push open brackets in the stack. If the current character is ‘)’, we check whether the top element is an open bracket and pop it else, we add the current character index in the map. We also add the indices that are present in the stack. We print the valid string without adding the index present in the map.
The basic idea is to store the count of open. We keep the count of open brackets while traversing the string and decrease its count to balance it with the closed brackets. If the count of open brackets is zero and the current character is a closed bracket, we change the value of the character at that index (say, ‘#’). We also remove the extra open brackets from the end of the string to make the string valid. We print the string excluding the ‘#’ character.
Here is the algorithm :