Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1106: Parsing A Boolean Expression

In this guide, we solve Leetcode #1106 Parsing A Boolean Expression in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Stack, Recursion, String

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

Input: expression = "&(|(f))" Output: false Explanation: First, evaluate |(f) --> f. The expression is now "&(f)". Then, evaluate &(f) --> f. The expression is now "f". Finally, return false.

Python Solution

class Solution: def parseBoolExpr(self, expression: str) -> bool: stk = [] for c in expression: if c in 'tf!&|': stk.append(c) elif c == ')': t = f = 0 while stk[-1] in 'tf': t += stk[-1] == 't' f += stk[-1] == 'f' stk.pop() match stk.pop(): case '!': c = 't' if f else 'f' case '&': c = 'f' if f else 't' case '|': c = 't' if t else 'f' stk.append(c) return stk[0] == 't'

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy