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
Parsing A Boolean Expression INPUT expression = "|(f,t)" | (OR) f t Expression Tree Structure = true (t) = false (f) Operators: | = OR, & = AND, ! = NOT t = true, f = false ALGORITHM STEPS 1 Use Stack Push chars onto stack 2 Find Operator When ')' found, pop until '(' 3 Evaluate Apply operator to operands 4 Push Result Push result back to stack Stack Trace: Push: | ( f , t Pop until '(': f, t OR(f,t) = t --> Push t Result: t (true) FINAL RESULT Expression Evaluation: |(f, t) = OR(false, true) = true Output: true OK - Verified OR returns true if any operand is true t is true --> result: true Key Insight: Use a stack-based approach to parse nested boolean expressions. When encountering ')', pop operands until '(' is found, then apply the operator (|, &, !) to evaluate. Push the result back onto the stack. Time Complexity: O(n) where n is expression length. Space Complexity: O(n) for the stack. TutorialsPoint - Parsing A Boolean Expression | Optimal Solution (Stack-based)
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