

You are given a string of length ‘N’ containing only the following characters: ‘[’, ‘{’, ‘(’, ‘)’, ‘}’, ‘]’. At some places, there is ‘X’ in place of any bracket. Your task is to determine that if you replace all the X’s with appropriate brackets, is it possible to get a valid balanced sequence or not.
For example:
For the given string “[X)](X”, the possible replacement for the first X is ‘(‘ and the second X is ‘)’, which makes the sequence “[()]()”, which is a valid balanced sequence.
For the given string “[XX{”, there is no possible replacement for X which can make it a valid bracket sequence.
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.
The first and only line of each test case or query contains the string.
Output format:
For each test case, print “Valid” if a balanced sequence is possible, otherwise, print “Invalid”, without quotes in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just return 'True' for valid string and 'False' for an invalid string.
1 <= T <= 10
1 <= N <= 20
Time limit: 1 sec
2
{[X(X)]}
{[X](X)}
Valid
Invalid
For test case 1:
The correct valid bracket sequence is: { [ ( ( ) ) ] }
For test case 2:
No valid bracket sequence is possible.
2
[(X){}{{}}]
XX
Invalid
Valid
First off, observe that the question focuses on guessing what X can be and check if it makes the sequence balanced or not. The point here is that the possibilities can be either opening bracket, closing bracket or X and all we need to see is how to react in these 3 situations.
The idea is to use stack data structure and is pretty much similar to the algorithm where we check if the expression is balanced or not.
We mainly have 3 conditions to fulfil i.e.
Let us work on example “X(X)”
Initially, stack s = { }
Let the function definition be isValidHelper(String str, stack s, ele) where ele is the index of the current character on which we are working, initially,ele = 0.
O(2^N * N), where N is the size of the given string.
For every character ‘X’ in the string, we call the recursive function twice (considering ‘X’ as opening and closing bracket). In the worst case, all the characters of the string can be ‘X’. Hence, there would be O(2^N) recursive calls. Also for every recursive call we create a temporary copy of stack which requires O(N) time. Hence, the overall time complexity is O(2^N * N).
O(N), where N is the size of the given string.
Extra space is required for the recursion stack which goes upto a maximum depth of O(N). Also, O(N) space is required for the temporary stack. Hence, the overall space complexity is O(N).