oneby7

2-D Dynamic Programming Splitting a range

577. Ways to Evaluate a Boolean Expression to True

Hard

You are given a string expression of the values T (true) and F (false), with one operator between each pair of neighbouring values. The operators are & (and), | (or) and ^ (xor). An xor is true when exactly one of its two sides is true.

Put parentheses into the expression so that every operator joins exactly two parts. Each such grouping fixes the order in which the operators are applied. Two groupings are different when they group the values differently, even if they give the same result. For example, T|F&T has two groupings, (T|F)&T and T|(F&T).

Return the number of groupings that make the expression true. The count can be very large, so return it modulo 109 + 7.

Example 1

Input: expression = "T^F|T&F"

Output: 3

Explanation: Three groupings are true: (T^F)|(T&F), T^((F|T)&F) and T^(F|(T&F)). The other two, ((T^F)|T)&F and (T^(F|T))&F, end with &F, so they are false.

Example 2

Input: expression = "F"

Output: 0

Explanation: A single value has one grouping, the value itself, and here it is false.

Example 3

Input: expression = "T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T|T"

Output: 475387402

Explanation: Every grouping is true, because every value is true. There are 3814986502092304 groupings, and that count modulo 109 + 7 is 475387402.

Check your understanding

Work out the answer for this input before you write any code.

expression = "T&T&T&T"

Constraints

  • 1 ≤ expression.length ≤ 401
  • expression.length is odd.
  • The characters at even indexes are T or F, and the characters at odd indexes are &, | or ^.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.