Skip to main content
LeetCode 1106, Hard. Topics: String, Stack, Recursion. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 17 parametrized pytest cases, and a playground notebook:

Problem

A <strong>boolean expression</strong> is an expression that evaluates to either <code>true</code> or <code>false</code>. It can be in one of the following shapes:
  • <code>‘t’</code> that evaluates to <code>true</code>.
  • <code>‘f’</code> that evaluates to <code>false</code>.
  • <code>’!(subExpr)’</code> that evaluates to <strong>the logical NOT</strong> of the inner expression <code>subExpr</code>.
  • <code>’&(subExpr<sub>1</sub>, subExpr<sub>2</sub>, …, subExpr<sub>n</sub>)’</code> that evaluates to <strong>the logical AND</strong> of the inner expressions <code>subExpr<sub>1</sub>, subExpr<sub>2</sub>, …, subExpr<sub>n</sub></code> where <code>n >= 1</code>.
  • <code>’|(subExpr<sub>1</sub>, subExpr<sub>2</sub>, …, subExpr<sub>n</sub>)’</code> that evaluates to <strong>the logical OR</strong> of the inner expressions <code>subExpr<sub>1</sub>, subExpr<sub>2</sub>, …, subExpr<sub>n</sub></code> where <code>n >= 1</code>.
Given a string <code>expression</code> that represents a <strong>boolean expression</strong>, return <em>the evaluation of that expression</em>. It is <strong>guaranteed</strong> that the given expression is valid and follows the given rules.

Examples

Constraints

  • <code>1 <= expression.length <= 2 * 10<sup>4</sup></code>
  • <code>expression[i]</code> is one following characters: <code>’(’</code>, <code>’)’</code>, <code>’&’</code>, <code>’|’</code>, <code>’!’</code>, <code>‘t’</code>, <code>‘f’</code>, and <code>’,’</code>.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026