#1106
Parsing A Boolean Expression
HardStringStackRecursionStackRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a stack to manage the parsing of the expression, allowing us to evaluate it in a single pass. This avoids redundant evaluations and keeps track of the depth of nested expressions efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a stack to keep track of expressions and their results.
- 2Step 2: Iterate through the expression character by character, pushing operators and operands onto the stack.
- 3Step 3: When encountering a closing parenthesis, pop from the stack until the corresponding opening parenthesis is found, evaluate the expression, and push the result back onto the stack.
- 4Step 4: At the end of the iteration, the stack will contain the final result.
solution.py24 lines
1def parse(expression):
2 stack = []
3 i = 0
4 while i < len(expression):
5 if expression[i] in 'tf':
6 stack.append(expression[i] == 't')
7 elif expression[i] == '(':
8 stack.append(i)
9 elif expression[i] == ')':
10 inner = []
11 while stack and isinstance(stack[-1], bool):
12 inner.append(stack.pop())
13 inner.reverse()
14 operator = stack.pop()
15 if operator == '!':
16 stack.append(not inner[0])
17 elif operator == '&':
18 stack.append(all(inner))
19 elif operator == '|':
20 stack.append(any(inner))
21 else:
22 stack.append(expression[i])
23 i += 1
24 return stack[0]ℹ
Complexity note: This complexity is due to the single pass through the expression and the use of a stack to store intermediate results, which can grow with the depth of nested expressions.
- 1Understanding operator precedence is crucial.
- 2Recognizing the structure of nested expressions helps in parsing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.