You are given an expression 'exp' in the form of a string where operands will be : (TRUE or FALSE), and operators will be : (AND, OR or XOR).
Now you have to find the number of ways we can parenthesize the expression such that it will evaluate to TRUE.
As the answer can be very large, return the output modulo 1000000007.
Note :
‘T’ will represent the operand TRUE.
‘F’ will represent the operand FALSE.
‘|’ will represent the operator OR.
‘&’ will represent the operator AND.
‘^’ will represent the operator XOR.
Example :
Input: 'exp’ = "T|T & F".
Output: 1
Explanation:
There are total 2 ways to parenthesize this expression:
(i) (T | T) & (F) = F
(ii) (T) | (T & F) = T
Out of 2 ways, one will result in True, so we will return 1.
Input format:
The first line of each input contains a string representing the expression ‘exp’.
Output format:
print a single integer representing the number of ways we can parenthesize the expression to evaluate to true.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
T^T^F
0
There are total 2 ways to parenthesize this expression:
(i) (T^T)^(F) = F
(ii) (T)^(T^F) = F
Both ways will result in False, so we will return 0.
F|T^F
2
For the first test case:
There are total 2 ways to parenthesize this expression:
(i) (F|T)^(F) = T
(ii) (F)|(T^F) = T
Both ways will result in True, so we will return 2.
The expected time complexity is O(n ^ 3), where 'n' denotes the length of 'exp'.
3 <= |‘exp’| <= 200
Where |'exp'| denotes the length of 'exp'.
Time Limit: 1 sec
Can you try to think to find all combinations and then calculate?
Approach: Basically, we will divide the expression into smaller parts and will try to find the number of ways a smaller expression can result in True and the number of ways a smaller expression can result in False.
With the help of the result of the smaller expression, we will be able to find the number of ways the whole expression can result in True.
Let’s define a recursive function, ‘findWays’, which will receive the following parameter.
(i) ‘exp’ the given expression.
(ii) ‘st’ is an integer variable representing the starting point for the sub-expression.
(iii) ‘end’ is an integer variable representing the ending point for the sub-expression.
(iii) ‘isTrue’ is a bool variable representing whether the sub-expression should evaluate to True or False.
Base Condition :
Recursive Calls:
O(4^n), where ‘n’ is the size of the string.
As in each step, we are making 4 recursive calls till the value of ‘n’ for the current call is greater than 1, thus raising the time complexity to O(4^n).
Hence the final time complexity is O(4^n).
O(4^n), where ‘n’ is the size of the string.
This will be the space the recursion stack uses to save 4^'n' calls.
Hence the final space complexity is O(4^n).