Parsing A Boolean Expression - Problem

A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:

  • 't' that evaluates to true
  • 'f' that evaluates to false
  • '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr
  • '&(subExpr₁, subExpr₂, ..., subExprₙ)' that evaluates to the logical AND of the inner expressions subExpr₁, subExpr₂, ..., subExprₙ where n ≥ 1
  • '|(subExpr₁, subExpr₂, ..., subExprₙ)' that evaluates to the logical OR of the inner expressions subExpr₁, subExpr₂, ..., subExprₙ where n ≥ 1

Given a string expression that represents a boolean expression, return the evaluation of that expression.

It is guaranteed that the given expression is valid and follows the given rules.

Input & Output

Example 1 — OR Expression
$ Input: expression = "|(f,t)"
Output: true
💡 Note: OR operation with operands false and true: f | t = true
Example 2 — Nested AND with OR and NOT
$ Input: expression = "&(|(t,f,t),!(t))"
Output: false
💡 Note: First evaluate inner expressions: |(t,f,t) = true, !(t) = false. Then: &(true,false) = false
Example 3 — Complex Nesting
$ Input: expression = "|(!(f),&(t,t,t))"
Output: true
💡 Note: Inner expressions: !(f) = true, &(t,t,t) = true. Then: |(true,true) = true

Constraints

  • 1 ≤ expression.length ≤ 2 * 104
  • expression[i] is one of 't', 'f', '!', '&', '|', '(', ')', and ','
  • expression is a valid boolean expression

Visualization

Tap to expand
Boolean Expression Parsing: &(|(t,f,t),!(t))&(|(t,f,t),!(t))Step 1: Identify nested structure|(t,f,t) → true!(t) → falseStep 2: Evaluate inner expressions first&(true, false) = falseStep 3: Combine results with outer operator
Understanding the Visualization
1
Input Structure
Nested boolean expression with operators and operands
2
Parse & Evaluate
Process operators with their operands systematically
3
Boolean Result
Final true/false evaluation
Key Takeaway
🎯 Key Insight: Parse nested boolean expressions by handling operators and their operands systematically, evaluating from innermost expressions outward
Asked in
Facebook 12 Google 8 Amazon 6 Microsoft 4
32.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen