πDay 22. Boolean Parenthesization π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given a boolean expression s consisting of:
Operands:
'T'β True'F'β False
Operators:
'&'β Boolean AND'|'β Boolean OR'^'β Boolean XOR
Count the number of ways we can parenthesize the expression such that it evaluates to True.
π Example Walkthrough:
Example 1:
Input:
Output:
Explanation:
The expression evaluates to True in 4 ways:
((T | T) & (F ^ T)) β (T | T) β T, (F ^ T) β T, T & T = T β(T | (T & (F ^ T))) β (F ^ T) β T, (T & T) β T, T | T = T β(((T | T) & F) ^ T) β (T | T) β T, (T & F) β F, F ^ T = T β(T | ((T & F) ^ T)) β (T & F) β F, (F ^ T) β T, T | T = T β
Example 2:
Input:
Output:
Explanation:
The expression evaluates to True in 2 ways:
((T^F)|F)(T^(F|F))
Constraints:
$(1 \leq |s| \leq 100)$
π― My Approach:
The problem follows optimal substructure and overlapping subproblems, making Dynamic Programming (DP) the most efficient approach.
We use a bottom-up DP approach where we maintain two 2D DP tables:
T[i][j]β Number of ways to parenthesizes[i:j]to get True.F[i][j]β Number of ways to parenthesizes[i:j]to get False.
Algorithm Steps:
Initialize the DP tables:
If
s[i] == 'T', setT[i][i] = 1(since a singleTis alwaysTrue).If
s[i] == 'F', setF[i][i] = 1(since a singleFis alwaysFalse).
Fill the DP tables using a bottom-up approach:
Iterate over subexpressions of increasing length (
l), from 2 to n.For each subexpression
s[i:j], check each operators[k](wherekis an odd index).Compute
T[i][j]andF[i][j]using previously computed DP values.
Update DP values based on the operator
s[k]:If
s[k] == '&'(AND operator):T[i][j] += lt * rt(both left and right must be True).F[i][j] += lt * rf + lf * rt + lf * rf(any case where at least one is False).
If
s[k] == '|'(OR operator):T[i][j] += lt * rt + lt * rf + lf * rt(only both False make it False).F[i][j] += lf * rf.
If
s[k] == '^'(XOR operator):T[i][j] += lt * rf + lf * rt(one True, one False).F[i][j] += lt * rt + lf * rf(both True or both False).
Return
T[0][n-1], which gives the total ways to evaluatestoTrue.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(NΒ³), as we process all partitions
(i, k, j)for each segment ofs.Expected Auxiliary Space Complexity: O(NΒ²), for storing
TandFDP tables.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated