Parse Lisp Expression - Problem
You are given a string expression representing a Lisp-like expression. Your task is to return the integer value after evaluating this expression.
Expression Types:
- Integer: A positive or negative integer
- Variable: A string starting with lowercase letter, followed by lowercase letters or digits
- Let Expression:
(let v1 e1 v2 e2 ... vn en expr)- assigns variables sequentially, then evaluatesexpr - Add Expression:
(add e1 e2)- returns sum of two expressions - Mult Expression:
(mult e1 e2)- returns product of two expressions
Scoping Rules: Variables are resolved from innermost to outermost scope. The names add, let, and mult are reserved and will never be used as variable names.
Input & Output
Example 1 — Let Expression
$
Input:
expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"
›
Output:
14
💡 Note:
Outer scope: x=2. Inner scope: x=3, y=4. Inner expression: add(3,4)=7. Outer expression: mult(2,7)=14.
Example 2 — Nested Add
$
Input:
expression = "(add 1 (mult 2 3))"
›
Output:
7
💡 Note:
First evaluate mult(2,3)=6, then add(1,6)=7.
Example 3 — Variable Scoping
$
Input:
expression = "(let x 3 x 2 x)"
›
Output:
2
💡 Note:
Variable x is reassigned: first x=3, then x=2. Final expression evaluates x which is 2.
Constraints
- 1 ≤ expression.length ≤ 2000
- The expression is syntactically correct
- All integers are within the 32-bit signed integer range
Visualization
Tap to expand
Understanding the Visualization
1
Input
Nested Lisp expression with variables and operations
2
Parse
Recursive parsing with variable scope management
3
Output
Final integer result after evaluation
Key Takeaway
🎯 Key Insight: Use recursive parsing to naturally handle nested structure and variable scoping
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code