Problem of the day
You are given a string consisting only of parentheses and letters. Your task is to remove the minimum number of invalid parentheses and return all possible unique, valid strings thus obtained.
Note:
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.
Input Format
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.
Output Format:
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.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= |STR| <= 50
Time Limit: 1 second
2
(((a))()
)(()))
(((a))) ((a))()
(())
Test Case 1 :
Given ‘STR’ = (((a))()
From this string, two valid strings can be generated after removing only one parenthesis, which is minimum.
One way is to remove the parenthesis at index 6 to generate (((a))).
Another way is to remove either the first, second, or third parenthesis, which will result in the same string, i.e., ((a))().
Test Case 2 :
Given ‘STR’ = )(()))
The minimum number of invalid parentheses required to be removed is 2. We have to remove the first and last parentheses to generate a valid string.
So the valid string is (()).
1
(()(()(())
()()(()) ()(()()) (())(()) (()()()) (()(()))
Can you think of a similar approach that, by default, guarantees minimum removal of parentheses by considering strings level by level?
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) :
O(N * (2 ^ N - 1)), where ‘N’ is the number of parentheses in the string.
Checking whether a string is valid or not will take O(N) time at each level. And, for every string of length N, we will have (N - 1) strings at the next level, i.e., C(N, N - 1) at the second level, C(N, N-2) at the third level, and so on.
Therefore, total time = N * C(N, N) + (N - 1) * C(N, N - 1) + (N - 2) * C(N, N - 2) + . . . + 1 * C(N, 1) = N * (2 ^ (N - 1)).
O(N), where ‘N’ is the number of parentheses in the string.
We are using a queue that can take O(N) space in the worst case.