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
Difficulty
and has an acceptance rate of about 70% (200k+ submissions).
Typical patterns to solve this problem:
- Recursion
- Stack
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
Extra
- 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