Boolean Parenthesization

Implement countWays

You're given a boolean expression as a string, alternating symbols (T for True, F for False) with operators (&, |, ^ for AND, OR, XOR) — for example "T|T&F". Count how many distinct ways to fully parenthesize the expression make it evaluate to True. The number of parenthesizations of an n-symbol expression grows the same way binary tree shapes do — far too many to enumerate directly once n gets past single digits. The way out is to stop asking "what's the final value" and instead ask two questions about every stretch of the expression at once: in how many ways can it read True, and in how many ways can it read False? Knowing both counts for two adjacent stretches is exactly what's needed to combine them correctly through whichever operator joins them — AND only succeeds when both sides do, OR fails only when both sides do, and XOR succeeds on exactly the two "mismatched" combinations. Building those True/False pairs from the smallest stretches (single symbols) up to the whole expression means every stretch is only ever solved once.

Example 1:

Input: expr = "T|T&F"

Output: 1

Example 2:

Input: expr = "T"

Output: 1

Example 3:

Input: expr = "F"

Output: 0

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of boolean symbols in expr ≤ 8
  • expr alternates T/F symbols with &, |, ^ operators, and always starts and ends with a symbol (e.g. "T|T&F")
  • the answer always fits comfortably in a normal 32-bit int at this size — no modulo needed

expr =

T|T&F