Problem of the day
You are given a string ‘S’ consisting of lowercase alphabets, “(“ and “)”. You need to remove the minimum number of parentheses to make the string valid and print that valid string.
A string is valid iff:
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.
For example :
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’.
Output Format :
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.
Note :
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
2
co(di()ng
nin())jas
co(di)ng
nin()jas
For test case 1:
The valid string can be: “co(di)ng” or “codi()ng”.
For test case 2:
The valid string will be: “nin()jas”.
2
st()))ick
abc
st()ick
abc
Try to check all the possibilities by removing the brackets.
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:
Here is the algorithm :
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).
O((2 ^N ) * N), where ‘N’ is the size of the string.
Every character equal to ‘(‘ or ‘)’ of the string has two choices, whether to include it in a string or not. There are total ‘N’ characters, so the number of possible combinations will be 2 * 2 * 2… (‘N’ times). And for every string, we check whether it is valid or not, which takes O(N) time. Therefore, the overall time complexity will be O((2 ^ N) * N).
O(N), where ‘N’ is the size of the string.
The recursive stack for the HELPER function can contain the length of the string at most. Therefore, the overall space complexity will be O(N).