


1) A string is valid only if every left parenthesis has corresponding right parentheses in the same order.
For example Given ‘STR’ = (())()) is not a valid string, whereas ‘STR’ = (())() is a valid string.
The first line of input contains an integer 'T' representing the number of test cases.
The first and the only line of each test case contains a single string ‘STR’ representing the parenthesis.
For each test case, return all possible unique, valid strings after removing the minimum number of parentheses.
The output of each test case will be printed 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 <= 5
1 <= |STR| <= 50
Time Limit: 1 second
The idea here is to use the BFS algorithm. Using BFS, we will move through states level by the level that will ensure the removal of the minimal number of parentheses. At each level, we will remove only one parenthesis. So, if we found a valid string, we will restrict ourselves to that level only.
Please note that the overhead to pass parameters in a recursive call is also avoided because of BFS.
Algorithm:
Description of ‘IS_VALID_STRING’ function
This function will take one parameter :
bool IS_VALID_STRING(STR) :
The idea is to explore all the possibilities by keeping two options for each parenthesis, i.e., to include or exclude. This provides us with a thought to use recursion and backtracking to solve this problem.
To check for a valid string, we will maintain the count of left and right parentheses. At any instant, if the number of left parentheses is equal to the number of right parentheses, then the string is valid; otherwise, not.
We should also keep in mind that if the number of right parentheses is greater than the number of left parentheses, then the string can never be valid. At that instant, we do not need to recur forward.
For keeping track of unique strings, we will use a hash set (i.e., unordered_set in c++).
Algorithm:
Description of ‘REMOVE_RECURSIVELY’ function
This function will take seven parameters :
void REMOVE_RECURSIVELY(STR, INDEX, RESULT_SO_FAR, LEFT_COUNT, RIGHT_COUNT, REMOVE_COUNT, HASH_SET):
The idea here is to determine the number of left and right misplaced parentheses. After that, we no longer need to check for the global minimum and update the hash set. We can be sure that if the count of both left and right misplaced parentheses reduces to zero, then the string is valid and of maximum length (formed by minimum removals).
The optimized backtracking approach will be similar to approach 1 with some modifications.
Algorithm:
Description of ‘REMOVE_RECURSIVELY’ function
This function will take eight parameters :
void REMOVE_RECURSIVELY(STR, INDEX, RESULT_SO_FAR, LEFT_MISPLACED, RIGHT_MISPLACED, LEFT_COUNT, RIGHT_COUNT, HASH_SET):