Parsing A Boolean Expression

Hard Topics Company Tags

Evaluate the valid boolean expression in expression. The literals t and f mean true and false. The form !(x) negates its single argument. The form &(x,y,...) is true when all its arguments are true, and |(x,y,...) is true when at least one argument is true. AND and OR have one or more comma-separated arguments. Arguments can themselves be expressions, so parentheses determine the nesting. Return the resulting boolean value.

Example 1:

Input: expression = "!(&(t,t))"

Output: false

Explanation: The inner AND is true because both inputs are true. Negating that result gives false.

Example 2:

Input: expression = "&(t,|(f,t))"

Output: true

Explanation: The inner OR is true because one input is true. The outer AND combines true with true, so return true.

Example 3:

Input: expression = "|(&(t,f),!(f))"

Output: true

Explanation: The AND on the left is false, while the NOT on the right turns false into true. OR combines false and true to produce true.

Constraints:

  • 1 <= expression.length <= 20000
  • Only t, f, !, &, |, (, ), and , occur.
  • The expression obeys the grammar above and is valid.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.