Ninja has recently learnt about sequences of parentheses. These are special sequences that contain only the characters '(' and ')'.
Ninja studied regular and non-regular sequences of parentheses too. A regular sequence follows the following definition :
An empty sequence is regular :
If βSβ is a regular sequence, then (S) is also regular.
If βAβ and βBβ represent two regular sequences, then their concatenation βABβ is also regular.
Therefore, the sequences (), ()() and (())() are regular, while ()(, ) and ))() are non-regular.
Now Ninja provides you with a parentheses sequence βSβ of length βNβ and challenges you to find the longest subsequence of the given sequence which is non-regular. Amongst all such distinct subsequences, output the lexicographically βKthβ amongst them. If the number of distinct subsequences with maximum length is less than βKβ, please output -1 instead.
Note :β(β is considered lexicographically smaller than β)β.
Two subsequences are distinct if they differ at least at one of the indexes. E.g. β))β and β((β are distinct whereas β((β and β((β are not.
Example :
N = 5
S = ()
K = 2
Explanation :
All possible subsequences of the given sequence are : β(β , β)β and β()β.
The non-regular subsequences among these are : β(β and β)β.
Of these the lexicographically β2ndβ subsequence is β)β.
Hence, final result = β)β.
The first line contains an integer 'T' which denotes the number of test cases to be run. Then the test cases follow.
The first line of each test case contains two integers βNβ and βKβ.
The second line of each test case contains a string βSβ of length βNβ.
Output format :
For each test case, print a string denoting the lexicographically βKthβ non-regular subsequence of string βSβ.
Print the output of each test case in a new line.
Note :
You donβt need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1β<= N <= 10^5
1 <= K <= 10^9
S[i] = β(β or S[i] = β)β.
Time Limit : 1 sec
2
3 2
(()
4 2
(())
-1
())
For test case 1 we have,
The largest non-regular subsequence is (().
There exists only 1 largest length non-regular subsequence but we need to find the 2nd non-regular subsequence.
So we output -1.
For test case 2 we have,
The largest non-regular subsequence length is 3 and there are two such unique subsequences. They are (() and ()) respectively in lexicographic order.
We are required to print the β2ndβ subsequence.
So we output ()).
2
2 2
()
3 1
(()
)
(()
Find all subsequences of the sequence.
Approach :
Algorithm :
O(N*2^N) , where βNβ is the length of string βSβ.
We are calculating all possible subsequences and checking if they are regular or not, so the overall time complexity is O( N*2^N ).
O(N)
There can be maximum βNβ non-regular strings of maximum length.Hence, the overall Space Complexity is O(N).