


‘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.
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.
The first line of each input contains a string representing the expression ‘exp’.
print a single integer representing the number of ways we can parenthesize the expression to evaluate to true.
You do not need to print anything, it has already been taken care of. Just implement the given function.
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.
Approach: Our last approach was very simple and easy, but its time complexity was of exponential order. We can improve our solution by taking care of the overlapping subproblems. Thus, we will eliminate the need for solving the same subproblems again and again by storing them in a lookup table. This approach is known as Memoization.
We will initialize a 3-D array, say ‘memo’ [n][n][2] with -1, where ‘n' is the size of string ‘exp’.Where ‘memo’[i][j][k] equal to -1 means the current state is not explored. Otherwise, ‘memo’[i][j][0] will store the number of ways expression(i, j) will be false, and ‘memo’[i][j][1] will store the number of ways expression(i, j) will be True.
So there will be two modifications to the earlier approach :
Algorithm: