Problem 1106

Abstract / Summary

Parse a boolean expression string to determine if it can be evaluated true false or false without ambiguity.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1106.py

class Solution:
    def parseBoolExpr(self, expression: str) -> bool:
        expression = expression.replace("f", "0")
        expression = expression.replace("t", "1")
        expression = expression.replace("!", "1-")
        expression = expression.replace("&(", "min(1,")
        expression = expression.replace("|(", "max(0,")
        return eval(expression) == 1
8 lines | 378 bytes | submitted September 28, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (200k+ submissions).

Typical patterns to solve this problem:
  • Recursion
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation converts a Boolean expression written with the symbols t, f, !, &, | and parentheses into a Python arithmetic expression that can be evaluated directly. By mapping true/false to 1/0 and logical operators to the built-in functions min and max, the solution leverages Python’s interpreter to compute the result in a single step.

Key Transformation Steps

The method performs a series of string replacements that progressively reshape the original expression.

expression = expression.replace("f", "0")

All occurrences of the literal false are turned into the integer 0. This substitution prepares the expression for numeric evaluation.

expression = expression.replace("t", "1")

Similarly, the literal true is replaced with the integer 1. At this point the expression consists solely of digits, parentheses, commas, and operator symbols.

expression = expression.replace("!", "1-")

The logical NOT operator is expressed as 1- because 1-0 yields 1 (the negation of false) and 1-1 yields 0 (the negation of true). By placing 1- directly before the sub-expression, the code creates a valid arithmetic negation.

expression = expression.replace("&(", "min(1,")

The logical AND operator is mapped to the built-in min function. Since min returns the smallest argument, min(1, a, b, …) will be 1 only when every argument is 1; any 0 forces the result to 0. The replacement changes the opening of an AND clause while preserving the surrounding parentheses and commas.

expression = expression.replace("|(", "max(0,")

The logical OR operator is mapped to max. Because max returns the largest argument, max(0, a, b, …) evaluates to 1 if any argument is 1; otherwise it stays 0. This replacement mirrors the approach used for AND.

Finally, the transformed string is handed to Python’s evaluator:

return eval(expression) == 1

eval computes the arithmetic expression, producing either 0 or 1. The comparison with 1 converts the numeric result back into a Boolean value as required by the method’s signature.

Edge Cases Handled

The replacement strategy naturally accommodates nested expressions because each operator’s opening token (&( or |() is rewritten to a function call that can contain further calls as arguments. For example, an expression like &(t,|(f,!(t))) becomes min(1,1,max(0,0,1-1)), which eval resolves correctly.

The NOT transformation works for any sub-expression, including those that are themselves complex, because the 1- prefix is placed directly before the opening parenthesis of the operand.

Multiple operands for AND and OR are supported without additional logic; min and max accept a variable number of arguments, so expressions such as &(t,f,t) are converted to min(1,1,0,1) and evaluated as expected.

The code also tolerates expressions that consist of a single literal (t or f) because the replacement steps reduce them to 1 or 0, and eval returns the same value, which the final comparison correctly interprets.

Performance Optimizations

By relying on Python’s built-in string replacement functions, the transformation phase runs in linear time relative to the length of the input, avoiding the overhead of manual tokenization or parsing loops.

The use of min and max delegates the core logical aggregation to highly optimized C implementations within the Python runtime, which are faster than equivalent Python-level loops.

Calling eval once eliminates the need for iterative processing of the expression tree; the interpreter parses and computes the entire expression in a single pass, leveraging internal optimizations such as bytecode compilation and fast numeric operations.

Overall, the solution achieves a concise implementation that benefits from the efficiency of native Python constructs while maintaining clarity in the transformation logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine this computer program is like a clever translator making sense of a secret code. The code starts with some funny symbols like f and t, which are just short ways of saying false and true. The translator goes through the whole string and swaps those shortcut letters into numbers that the computer understands better. When it sees an exclamation mark, it treats that as a way to flip things around. When it sees those brackets with an ampersand or a pipe symbol, it turns them into math problems that find the smallest or biggest numbers in a group. By the time the computer finishes swapping all these pieces, it has a simple math sentence that it can solve to see if the final answer is true.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 4 | μ = 4.38 | σ = 1.82

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
withaarzoo C++
28 links | 16 authors | 9 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

32 solutions   September 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality