Boolean Parenthesization | Practice | GeeksforGeeks

Given a boolean expression S of length N with following symbols.
Symbols
    'T' ---> true
    'F' ---> false
and following operators filled between symbols
Operators
    &   ---> boolean AND
    |   ---> boolean OR
    ^   ---> boolean XOR
Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true.
 
Example 1:
Input: N = 7
S = T|T&F^T
Output: 4
Explaination: The expression evaluates 
to true in 4 ways ((T|T)&(F^T)), 
(T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)).
Example 2:
Input: N = 5
S = T^F|F
Output: 2
Explaination: ((T^F)|F) and (T^(F|F)) are the 
only ways.
 
Your Task:
You do not need to read input or print anything. Your task is to complete the function countWays() which takes N and S as input parameters and returns number of possible ways modulo 1003.
 
Expected Time Complexity: O(N3)
Expected Auxiliary Space: O(N2)
 
Constraints:
1 ≤ N ≤ 200 
0
milindprajapatmst191 week ago
const int N = 200, MOD = 1003;
int dp[N + 1][N + 1][2];

int _add(int x, int y) {
    return (x + y) % MOD;
}
int _mul(int x, int y) {
    return (x * y) % MOD;
}

class Solution {
public:
    int countWays(int n, string& str, int i = 0, bool k = 1) {
        if (i == n - 1) {
            if (k)
                return str[i] == 'T';
            else
                return str[i] == 'F';
        }
        if (dp[n][i][k] == -1) {
            int result = 0;
            for (int j = i + 1; j < n; j += 2) {
                if (str[j] == '&') {
                    if (k)
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 1)));
                    else {
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 0)));
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 1)));
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 0)));
                    }
                }
                else if (str[j] == '|') {
                    if (k) {
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 0)));
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 1)));
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 1)));
                    }
                    else
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 0)));
                }
                else if (str[j] == '^') {
                    if (k) {
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 0)));
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 1)));
                    }
                    else {
                        result = _add(result, _mul(countWays(j, str, i, 1), countWays(n, str, j + 1, 1)));
                        result = _add(result, _mul(countWays(j, str, i, 0), countWays(n, str, j + 1, 0)));
                    }
                }
            }
            dp[n][i][k] = result;
        }
        return dp[n][i][k];
    }
    Solution() {
        memset(dp, -1, sizeof(dp));
    }
};
0
divyansh1923cse10022 weeks ago
Python Easy Solution 
class Solution:
    def countWays(self, N, S):
        # code here
        d={}
        def solve(S,i,j,bol):
            if i>j:
                return 0
            if i==j:
                if S[i]==bol:
                    return 1
                else:
                    return 0
            s=""
            s+=str(i)+" "+str(j)+" "+bol
            if s in d:
                return d[s]
            ans=0
            for k in range(i+1,j,2):
                lt=solve(S,i,k-1,"T")
                lf=solve(S,i,k-1,"F")
                rt=solve(S,k+1,j,"T")
                rf=solve(S,k+1,j,"F")
                
                if S[k]=="&":
                    if bol=="T":
                        ans+=lt*rt
                    else:
                        ans+=lt*rf + lf*rt +lf*rf
                if S[k]=="|":
                    if bol=="T":
                        ans+=lt*rt +lf*rt +lt *rf
                    else:
                        ans+=lf*rf
                if S[k]=="^":
                    if bol=="T":
                        ans+=lt*rf +lf*rt
                    else:
                        ans+=lt*rt + lf*rf
            d[s]=ans
            return ans
        return solve(S,0,N-1,"T")%1003
0
redockp3 weeks ago
Why i am getting wrong answer
 
class Solution{public:   unordered_map<string,int>mp;   int mod=1003;   int solve(string s,int i,int j,bool isTrue){       if(i>j)       return 0;       if(i==j){           if(isTrue==true)               return s[i]=='T';           else               return s[i]=='F';       }          int ans=0;       string temp=to_string(i)+' '+to_string(j)+' '+to_string(isTrue);              if(mp.find(temp)!=mp.end())           return mp[temp];              for(int k=i+1;k<=j-1;k+=2){           int lt=solve(s,i,k-1,true);           int lf=solve(s,i,k-1,false);           int rt=solve(s,k+1,j,true);           int rf=solve(s,k+1,j,false);                                 if(s[k]=='&'){               if(isTrue==true)               ans=ans+(lt*rt);               else               ans=ans+(lf*rf)+(lt*rf)+(lf*rt);           }          else if(s[k]=='|'){               if(isTrue==true)               ans=ans+(lt*rt)+(lt*rf)+(lf*rt);               else               ans=ans+(lf*rf);                                         }           else if(s[k]=='^'){               if(isTrue==true)               ans=ans+(lt*rf)+(lf+rt);               else               ans=ans+(lf*rf)+(lt*rt);           }       }           return mp[temp]=ans%mod;          }   int countWays(int N, string S){       mp.clear();       return solve(S,0,N-1,true)%mod;   }};
0
neerajkhatri1803 weeks ago
class Solution{public:
   unordered_map<string,int> mp;      int solve(string s,int i,int j,char isTrue)   {       if(i>j)        return 0;       if(i==j)       {           if(isTrue=='T')            return s[i]=='T';           else            return s[i]=='F';       }               string tmp=to_string(i)+" "+to_string(j)+" "+to_string(isTrue);       if(mp.find(tmp)!=mp.end())        return mp[tmp];               int ans=0;       for(int k=i+1;k<j;k+=2)       {           int lT=solve(s,i,k-1,'T');           int lF=solve(s,i,k-1,'F');           int rT=solve(s,k+1,j,'T');           int rF=solve(s,k+1,j,'F');                      if(s[k]=='&')           {               if(isTrue=='T')                ans+=lT*rT;               else                ans+=lT*rF + lF*rT +lF*rF;           }           else           if(s[k]=='|')           {               if(isTrue=='T')                ans+=lT*rF + lF*rT +lT*rT;               else                ans+=lF*rF;           }           else           if(s[k]=='^')           {               if(isTrue=='T')                ans+=lT*rF + lF*rT;               else                ans+=lF*rF + lT*rT;           }       }       return mp[tmp]=ans%1003;   }
   int countWays(int N, string S){       // code here       mp.clear();      return solve(S,0,N-1,'T');   }};
0
noobcoder31201 month ago
Java Solution: 
Using 3D matrixUsing Map
Using 3D matrix
Using Map
class Solution{
    static int findWays(String str, int i, int j, boolean isTrue, int[][][] dp) {
        if(dp[i][j][isTrue ? 0 : 1] != -1) {
            return dp[i][j][isTrue ? 0 : 1];
        }
        if(i > j) {
            return dp[i][j][isTrue ? 0 : 1] = 0;
        }
        if(i == j) {
            char sign = str.charAt(i);
            if(isTrue && sign == 'T') {
                return dp[i][j][0] = 1;
            }
            if(!isTrue && sign == 'F') {
                return dp[i][j][1] = 1;
            }
            return dp[i][j][isTrue ? 0 : 1] = 0;
        }
        int ans = 0;
        for(int k = i + 1; k < j; k += 2) {
            int leftTrue, leftFalse, rightTrue, rightFalse;
			if(dp[i][k - 1][0] != -1) {
			    leftTrue = dp[i][k - 1][0];
			}
			else {
			    leftTrue = dp[i][k - 1][0] = findWays(str, i, k - 1, true, dp);
			}
			if(dp[i][k - 1][1] != -1) {
			    leftFalse = dp[i][k - 1][1];
			}
			else {
			    leftFalse = dp[i][k - 1][1] = findWays(str, i, k - 1, false, dp);
			}
			if(dp[k + 1][j][0] != -1) {
			    rightTrue = dp[k + 1][j][0];
			}
			else {
			    rightTrue = dp[k + 1][j][0] = findWays(str, k + 1, j, true, dp);
			}
			if(dp[k + 1][j][1] != -1) {
			    rightFalse = dp[k + 1][j][1];
			}
			else {
			    rightFalse = dp[k + 1][j][1] = findWays(str, k + 1, j, false, dp);
			}
			
			char operation = str.charAt(k);
			
            if(operation == '&') {
                if(isTrue) {
                    ans += (leftTrue * rightTrue);
                } else {
                    ans += (leftTrue * rightFalse + leftFalse * rightTrue + leftFalse * rightFalse);
                }
            } else if(operation == '|') {
                if(isTrue) {
                    ans += (leftTrue * rightFalse + leftFalse * rightTrue + leftTrue * rightTrue);
                } else {
                    ans += (leftFalse * rightFalse);
                }
            } else if(operation == '^') {
                if(isTrue) {
                    ans += (leftTrue * rightFalse + leftFalse * rightTrue);
                } else {
                    ans += (leftFalse * rightFalse + leftTrue * rightTrue);
                }
            }
        }
        return dp[i][j][isTrue ? 0 : 1] = ans % 1003;
    }
    static int countWays(int N, String S){
        // code here
        int[][][] dp = new int[S.length() + 1][S.length() + 1][2];
        for(int[][] a : dp) {
            for(int i = 0; i < a.length; i++) {
                a[i][0] = -1;
                a[i][1] = -1;
            }
        }
        return findWays(S, 0, S.length() - 1, true, dp) % 1003;
    }
}
class Solution{
    static HashMap<String, Integer> map;
    static int numOfWaysForTrueBUDPMap(String str, int i, int j, boolean isTrue) {
		String temp = new String(i + "_" + j + "_" + isTrue);
		if(map.containsKey(temp)) {
			return map.get(temp);
		}
		if(i > j) {
			map.put(temp, 0);
			return 0;
		}
		if(i == j) {
			char sign = str.charAt(i);
			if(isTrue && sign == 'T') {
				map.put(temp, 1);
				return 1;
			}
			if(!isTrue && sign == 'F') {
				map.put(temp, 1);
				return 1;
			}
			map.put(temp, 0);
			return 0;
		}

		int ans = 0;
		for(int k = i + 1; k < j; k += 2) {
			int leftFalse, leftTrue, rightFalse, rightTrue;
			String left1 = new String(i + "_" + (k - 1) + "_true"), left2 = new String(i + "_" + (k - 1) + "_false");
			String right1 = new String((k + 1) + "_" + j + "_true"), right2 = new String((k + 1) + "_" + j + "_false");
			if(map.containsKey(left1)) {
				leftTrue = map.get(left1);
			} else {
				leftTrue = numOfWaysForTrueBUDPMap(str, i, k - 1, true) % 1003;
				map.put(left1, leftTrue);
			}
			if(map.containsKey(left2)) {
				leftFalse = map.get(left2);
			} else {
				leftFalse = numOfWaysForTrueBUDPMap(str, i, k - 1, false) % 1003;
				map.put(left2, leftFalse);
			}
			if(map.containsKey(right1)) {
				rightTrue = map.get(right1);
			} else {
				rightTrue = numOfWaysForTrueBUDPMap(str, k + 1, j, true) % 1003;
				map.put(right1, rightTrue);
			}
			if(map.containsKey(right2)) {
				rightFalse = map.get(right2);
			} else {
				rightFalse = numOfWaysForTrueBUDPMap(str, k + 1, j, false) % 1003;
				map.put(right2, rightFalse);
			}

			char operation = str.charAt(k);
			if(operation == '&') {
				if(isTrue) {
					ans += (leftTrue * rightTrue);
				} else {
					ans += (leftFalse * rightTrue + leftTrue * rightFalse + leftFalse * rightFalse);
				}
			} else if(operation == '|') {
				if(isTrue) {
					ans += (leftTrue * rightFalse + leftFalse * rightTrue + leftTrue * rightTrue);
				} else {
					ans += (leftFalse * rightFalse);
				}
			} else if(operation == '^') {
				if(isTrue) {
					ans += (leftFalse * rightTrue + leftTrue * rightFalse); 
				} else {
					ans += (leftTrue * rightTrue + leftFalse * rightFalse);
				}
			}
		}

		map.put(temp, ans % 1003);
		return ans;
	}
	
    static int countWays(int N, String S){
        // code here
        map = new HashMap<String, Integer>();
        return numOfWaysForTrueBUDPMap(S, 0, S.length() - 1, true) % 1003;
    }
}
+1
amanasati11 month ago
Dont forget that mod 1003 :)
+3
shrustis1761 month ago
C++ solution (Aditya Verma)
 
We need to use mod 1003 as it is mentioned in question's Mytask section
 
// User function Template for C++
class Solution{public:unordered_map<string,int> mp;int mod = 1003;
int solve(string s, int i, int j, bool isTrue){   //BC   if(i>j)       return 0;   if(i==j)   {       if(isTrue == true)           return s[i]=='T';       else           return s[i] =='F';   }      string temp = to_string(i);   temp.push_back(' ');   temp.append(to_string(j));   temp.push_back(' ');   temp.append(to_string(isTrue));         if(mp.find(temp) != mp.end())       return mp[temp];      int ans=0;   for(int k=i+1; k<=j-1; k=k+2)   {      int lT=solve(s,i,k-1,true);      int lF=solve(s,i,k-1,false);      int rT=solve(s,k+1,j,true);      int rF=solve(s,k+1,j,false);            if(s[k] == '&')      {          if(isTrue == true)              ans= ans+ (lT*rT);                    else              ans=ans + (lF*rF) + (lF*rT) + (lT*rF);                }            else if(s[k] == '|')      {          if(isTrue == true)              ans=ans+ (lT*rT) + (lF*rT) + (lT*rF);                   else              ans=ans + (lF*rF);                }            else if(s[k]=='^')      {           if(isTrue == true)              ans=ans +(lF*rT) + (lT*rF);                   else              ans=ans+ (lF*rF)+ (lT*rT);                }   }      return mp[temp] = ans %mod;   }   int countWays(int N, string S){       // code here       mp.clear();              return solve(S,0,N-1,true)%mod;   }};
 
+3
ani145agrawal1 month ago
take mod by 1003 
i was stuck  in this for 1 hour and i wasn't able to find the answer 
0
harshdeepraghuwanshi1 month ago
can someone help me where i am getting wrong?
class Solution{
public:
      pair<int,int>  check(pair<int,int> &a,char x,pair<int,int> &b)
      {
          pair<int,int> ans;
          if(x=='^')
          {
              //T=T^F+F^T
              ans.first=a.first*b.second+a.second*b.first;
              //F=T^T+F^F
              ans.second=a.first*b.first+a.second*b.second;
              
          }
          else if(x=='&')
          {
              //T=T&T
              ans.first=a.first*b.first;
              ans.second=a.first*b.second+a.second*b.first+a.second*b.second;
          }
          else
          {
              ans.first=a.first*b.second+a.second*b.first+a.first*b.first;
              ans.second=a.second*b.second;
          }
          return ans;
      }
    int countWays(int N, string s){
        int size=N/2+1,k;
        pair<int,int> dp[size][size],ans; //first =true count //second =false count
        for(int g=0;g<size;g++)
        {
            for(int i=0,j=g;j<size;j++,i++)
            {
                if(g==0)
                {
                    if(s[2*i]=='T')
                    dp[i][j]={1,0};
                    else
                    dp[i][j]={0,1};
                }
                else if(g==1)
                {
                    dp[i][j]=check(dp[i+1][j],s[2*i+1],dp[i][j-1]);
                }
                else
                {
                    dp[i][j]={0,0};
                    for(int k=i;k<j;k++)
                    {
                       
                        ans=check(dp[i][k],s[2*k+1],dp[k+1][j]);
                        dp[i][j].first+=ans.first;
                        dp[i][j].second+=ans.second;
                    }
                }
            }
        }
        return dp[0][size-1].first;
    }
};
0
ashutoshggg7
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.