Parsing A Boolean Expression - Problem
Parse and Evaluate Boolean Expressions

You're tasked with building a boolean expression evaluator that can process nested logical operations. Think of it as creating a mini-interpreter for boolean logic!

The expression language supports:
't' - evaluates to true
'f' - evaluates to false
'!(expr)' - logical NOT of the inner expression
'&(expr1,expr2,...)' - logical AND of all inner expressions
'|(expr1,expr2,...)' - logical OR of all inner expressions

Goal: Parse the given string expression and return its boolean evaluation result.

Example: "&(|(f))" → First evaluate |(f) which is false, then evaluate &(false) which is also false.

Input & Output

example_1.py — Simple AND operation
$ Input: expression = "&(|(f))"
Output: false
💡 Note: First evaluate the inner OR operation: |(f) = false (OR of just false is false). Then evaluate the outer AND: &(false) = false (AND of just false is false).
example_2.py — OR with multiple values
$ Input: expression = "|(f,f,f,t)"
Output: true
💡 Note: OR operation with four values: f,f,f,t. Since at least one value is true, the result is true.
example_3.py — Nested NOT operation
$ Input: expression = "!(&(f,t))"
Output: true
💡 Note: First evaluate inner AND: &(f,t) = false (both values must be true for AND). Then apply NOT: !(false) = true.

Constraints

  • 1 ≤ expression.length ≤ 2 × 104
  • expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','
  • The given string expression represents a valid boolean expression
  • All sub-expressions are guaranteed to be properly formatted

Visualization

Tap to expand
Boolean Expression Evaluation Flow&(|(f,t),!(t))Parse &Handle |(f,t)Handle !(t)|(f,t) = T!(t) = F&(T, F)= FALSEFinal Result: false
Understanding the Visualization
1
Read Expression
Start from left, identify if we see a boolean value or an operator
2
Handle Nesting
When we see an operator, parse everything inside its parentheses
3
Recursive Evaluation
For nested expressions, recursively evaluate inner parts first
4
Apply Logic
Use AND/OR/NOT operations on the boolean results
Key Takeaway
🎯 Key Insight: Use recursion with index tracking to naturally handle nested expressions - each recursive call processes one level of the expression tree, making the solution both elegant and efficient.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
72.0K Views
Medium-High Frequency
~18 min Avg. Time
2.8K 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