#736
Parse Lisp Expression
HardHash TableStringStackRecursionHash MapStack
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 current scope of variables and evaluates expressions in a single pass. This avoids redundant evaluations and efficiently handles nested expressions.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a stack to keep track of variable scopes.
- 2Step 2: Parse the expression and identify tokens based on parentheses balance.
- 3Step 3: For each token, evaluate it based on its type (integer, variable, let, add, mult) using the current scope.
- 4Step 4: Update the scope for let expressions and return the final evaluated result.
solution.py8 lines
1def evaluate(expression):
2 stack = [{}]
3 def parse(expr):
4 # Token parsing logic here
5 return tokens
6 tokens = parse(expression)
7 # Evaluation logic here
8 return resultℹ
Complexity note: The optimal solution runs in linear time because each character in the expression is processed once, and the space complexity accounts for the variable scope stack.
- 1Understanding token parsing is crucial for evaluating nested expressions.
- 2Managing variable scope with a stack allows for efficient evaluations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.